Springboot之接收json字符串的两种方式

第一种方式、通过关键字段@RequestBody,标明这个对象接收json字符串。还有第二种方式,直接通过request来获取流。在spring中,推荐使用。

1、通过@RequestBody 接收json
直接通过@RequestBody 的方式,直接将json的数据注入到了JSONObject里面了。

/**
 * 创建日期:2018年4月6日

 * 代码创建:黄聪

 * 功能描述:通过request的方式来获取到json数据

 * @param jsonobject 这个是阿里的 fastjson对象
 * @return
 */
@ResponseBody
@RequestMapping(value = "/json/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public String getByJSON(@RequestBody JSONObject jsonParam) {
    // 直接将json信息打印出来
    System.out.println(jsonParam.toJSONString());

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

    return result.toJSONString();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2、通过Request获取
通过request的对象来获取到输入流,然后将输入流的数据写入到字符串里面,最后转化为JSON对象。

/**
 * 创建日期:2018年4月6日

 * 代码创建:黄聪

 * 功能描述:通过HttpServletRequest 的方式来获取到json的数据

 * @param request
 * @return
 */
@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();
}

/**
 * 创建日期:2018年4月6日

 * 代码创建:黄聪

 * 功能描述:通过request来获取到json数据

 * @param request
 * @return
 */
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
3、测试
测试中,我访问了json和 request两个类,来获取反回的信息,可以卡懂啊,返回的 method字段不一样,我这么做是为了区分,我访问了两个方法,而不是一个方法,反回的Content-Type 是application/json;charset=UTF-8

参考文章
https://www.cnblogs.com/yoyotl/p/7026566.html

你可能感兴趣的:(Springboot之接收json字符串的两种方式)