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

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

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

/**
 * 创建日期:2018年4月6日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:通过request的方式来获取到json数据<br/>
 * @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日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:通过HttpServletRequest 的方式来获取到json的数据<br/>
 * @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日<br/>
 * 代码创建:黄聪<br/>
 * 功能描述:通过request来获取到json数据<br/>
 * @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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值