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数据到一个对象
JsonElement parse = new JsonParser().parse(jsonStr);
将parse强转成想要对应的对象Student student = new Gson().fromJson(jsonStr, Student.class);
直接传入要转的json对象和对应的Bean类String s = new Gson().toJson(student);
将一个类转换成json数据gson.toJson(map);
将一个Map转换成jsonmap = gson.fromJson(mapJson,Map.class);
将json转换成Map