spring接收json字符串的两种方式

一、前言

  前几天遇到一个问题,前端H5调用我的springboot一个接口(post方式,@RequestParameter接收参数),传入的参数接收不到。自己测试接口时使用postman的form-data传参(相当于前端的form表单提交)是没问题的。后得知前端传入的是json字符串才清楚了问题。

相当于jq ajax的:

注:JSON.stringify() 方法用于将 JavaScript 值转换为 JSON 字符串。

后来自己又查阅了一些资料,整理一下:

$.ajax 的参数contentType 和 dataType

  • contentType 主要设置你发送给服务器的格式
  • dataType设置你收到服务器数据的格式。

在 jquery 的 ajax 中, contentType都是默认的值:application/x-www-form-urlencoded,这种格式的特点就是,name/value 成为一组,每组之间用 & 联接,而 name与value 则是使用 = 连接。如: wwwh.baidu.com/q?key=fdsa&lang=zh 这是get , 而 post 请求则是使用请求体,参数不在 url 中,在请求体中的参数表现形式也是: key=fdsa&lang=zh的形式。

好了下面步入标题内容

二、spring接收json字符串的两种方式

1、通过@RequestBody 接收json

直接通过@RequestBody 的方式,直接将json的数据注入到了JSONObject或者用Map接收或者写一个入参的实体类bean对象接收里。

@RestController
@RequestMapping("/firstCon")
public class FirstCon {

    @RequestMapping(value = "/abc/get", method = RequestMethod.POST)
    public String get(@RequestBody Map o) {
        /*@RequestBody JSONObject o
          @RequestParameter("name") String name,@RequestParameter("sex") String sex //非json字符串接收方式 eg:get方式;post:form-data or application/x-www-form-urlencoded
          @RequestBody UserIn user //定义一个实体类接收*/
        String name = (String) o.get("name");
        String sex = (String) o.get("sex");
        return name + ";" + sex;
    }
}

2、通过Request获取

通过request的对象来获取到输入流,然后将输入流的数据写入到字符串里面,最后转化为JSON对象。

@ResponseBody
@RequestMapping(value = "/request/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String getByRequest(HttpServletRequest request) {

    //获取到JSONObject
    JSONObject jsonParam = this.getJSONParam(request);

    // 将获取的json数据封装一层,然后在给返回
    JSONObject result = new JSONObject();
    result.put("msg", "ok");
    result.put("method", "request");
    result.put("data", jsonParam);

    return result.toJSONString();
}

public JSONObject getJSONParam(HttpServletRequest request){
    JSONObject jsonParam = null;
    try {
        // 获取输入流
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

        // 写入数据到Stringbuilder
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = streamReader.readLine()) != null) {
            sb.append(line);
        }
        jsonParam = JSONObject.parseObject(sb.toString());
        // 直接将json信息打印出来
        System.out.println(jsonParam.toJSONString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jsonParam;
}

猜你喜欢

转载自www.cnblogs.com/java-jun-world2099/p/10245462.html