SpringMVC中Json数据的处理

SpringMVC中Json数据的处理

1.较为原始的方式是:

导入阿里的fastjson库,

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.62</version>
</dependency>

后端返回json数据

@RequestMapping("/demo1")
    public void demo1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1. 设置响应内容
        response.setContentType("application/json;charset=utf-8");

        //2. 拿流写回JSON字符串
        Map<String,String> data = new HashMap<>();
        data.put("name","张三");
        data.put("age", "20");

        String s = JSON.toJSONString(data);
        response.getWriter().write(s);
    }

2.使用Jackson或者Gson的json库

     <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

返回Json数据的代码:
需要使用@ResponseBody注解


@Controller
@RequestMapping("/j")
public class Demo3Controller {
    @RequestMapping("/s")
    @ResponseBody
    public Map<String,String> m1(){
        Map<String,String> data = new HashMap<>();
        data.put("name","ss");
        data.put("status","student");
        return data;
    }
}

3.利用Gson解析Json数据到一个对象

  1. JsonElement parse = new JsonParser().parse(jsonStr);
    将parse强转成想要对应的对象
  2. Student student = new Gson().fromJson(jsonStr, Student.class);
    直接传入要转的json对象和对应的Bean类
  3. String s = new Gson().toJson(student);
    将一个类转换成json数据
  4. gson.toJson(map);
    将一个Map转换成json
  5. map = gson.fromJson(mapJson,Map.class);
    将json转换成Map
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值