【SpringMVC】(七)JSON
JSON
- JSON(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式。
1.JSON和JavaScript对象互转
-
JSON转JS对象
var obj = JSON.parse('{"a":"Hello","b":"World"}'); //结果是 {a:'Hello',b:'World'} -
JS对象转JSON
var json = JSON.stringify({a:'Hello',b:'World'}); //结果是 '{"a":"Hello","b":"World"}'
2.Controller 返回JSON数据
测试环境搭建
-
导入依赖
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> -
springmvc配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="com.musecho.controller"/> <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/" /> <!--后缀--> <property name="suffix" value=".jsp" /> </bean> </beans> -
User
@Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; } -
UserController
@Controller public class UserController { @RequestMapping("/j1") @ResponseBody //加上这个注解,就不会走视图解析器,直接返回一个字符串 public String json1(){ User user = new User("zkk 1号",14,"女"); return user.toString(); } }
-
@ResponseBody:方法上方加这个注解,就不会走视图解析器,直接返回一个字符串 -
@RestController:类上方加这个注解,该类里所有的方法都不会走视图解析器,直接返回字符串。
(一)使用Jackson(json解析工具)
-
导入依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.1</version> </dependency> -
返回一个对象
@RequestMapping("/j1") @ResponseBody public String json1() throws JsonProcessingException { User user = new User("zkk 1号", 14, "女"); //jackson的ObjectMapper ObjectMapper mapper = new ObjectMapper(); String str = mapper.writeValueAsString(user); return str; }
-
返回集合
@RequestMapping("/j2") @ResponseBody public String json2() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); List<User> userList = new ArrayList<User>(); User user1 = new User("zkk 1号", 14, "女"); User user2 = new User("zkk 2号", 14, "女"); User user3 = new User("zkk 3号", 14, "女"); User user4 = new User("zkk 4号", 14, "女"); User user5 = new User("zkk 5号", 14, "女"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); String str=mapper.writeValueAsString(userList); return str; }
-
返回日期时间
1.使用java的方法格式化
@RequestMapping("/j3") @ResponseBody public String json3() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); Date date =new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //ObjectMapper,时间解析后的默认格式为:Timestamp,时间戳 return mapper.writeValueAsString(sdf.format(date)); }2.使用ObjectMapper的方法格式化
@RequestMapping("/j3") @ResponseBody public String json4() throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); //不使用时间戳的方式 mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //自定义日期格式对象 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //指定日期格式 mapper.setDateFormat(sdf); Date date = new Date(); String str = mapper.writeValueAsString(date); return str; }
-
抽象成一个json工具类
public class JsonUtils { public static String getJson(Object object) throws JsonProcessingException { return getJson(object, "yyyy-MM-dd HH:mm:ss"); } public static String getJson(Object object, String dateFormat) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); mapper.setDateFormat(sdf); return mapper.writeValueAsString(object); } }使用工具类后的方法
@RequestMapping(value = "/j1") @ResponseBody public String json1() throws JsonProcessingException { User user = new User("zkk 1号", 14, "女"); return JsonUtils.getJson(user); } @RequestMapping("/j2") @ResponseBody public String json2() throws JsonProcessingException { List<User> userList = new ArrayList<User>(); User user1 = new User("zkk 1号", 14, "女"); User user2 = new User("zkk 2号", 14, "女"); User user3 = new User("zkk 3号", 14, "女"); User user4 = new User("zkk 4号", 14, "女"); User user5 = new User("zkk 5号", 14, "女"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); return JsonUtils.getJson(userList); } @RequestMapping("/j3") @ResponseBody public String json3() throws JsonProcessingException { Date date = new Date(); String str = JsonUtils.getJson(date); return str; }
-
json乱码解决
1.方法级
//produces:指定响应体返回类型和编码 @RequestMapping(value = "/j1",produces = "application/json;charset = utf-8")
2.配置级:应用于全部
springmvc配置文件里加上
<!--JSON乱码问题配置--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
(二)FastJson
-
可以方便实现JSON对象与JavaBean对象的相互转换,实现JavaBean对象与JSON字符串的相互转换,实现JSON对象与JSON字符串的相互转换。
-
导入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency> -
方法
@RequestMapping("/j4") @ResponseBody public String json4() throws JsonProcessingException { List<User> userList = new ArrayList<User>(); User user1 = new User("zkk 1号", 14, "女"); User user2 = new User("zkk 2号", 14, "女"); User user3 = new User("zkk 3号", 14, "女"); User user4 = new User("zkk 4号", 14, "女"); userList.add(user1); userList.add(user2); userList.add(user3); userList.add(user4); System.out.println("=========Java对象转JSON字符串========="); String str1 = JSON.toJSONString(userList); System.out.println("JSON.toJSONString(userList) ==> " + str1); String str2 = JSON.toJSONString(user1); System.out.println("JSON.toJSONString(user1) ==> " + str2); System.out.println("=========JSON字符串转Java对象========="); User userConvert = JSON.parseObject(str2, User.class); System.out.println("JSON.parseObject(str2, User.class) ==> " + userConvert); System.out.println("=========Java对象转JSON对象========="); JSONObject jsonObject = (JSONObject) JSON.toJSON(user1); System.out.println(" (JSONObject) JSON.toJSON(user1) ==> " + jsonObject); System.out.println("=========JSON对象转Java对象========="); User userConvert2 = JSON.toJavaObject(jsonObject, User.class); System.out.println("JSON.toJavaObject(jsonObject, User.class) ==> " + userConvert2); return "Hello"; } -
打印结果
=========Java对象转JSON字符串========= JSON.toJSONString(userList) ==> [{"age":14,"name":"zkk 1号","sex":"女"},{"age":14,"name":"zkk 2号","sex":"女"},{"age":14,"name":"zkk 3号","sex":"女"},{"age":14,"name":"zkk 4号","sex":"女"}] JSON.toJSONString(user1) ==> {"age":14,"name":"zkk 1号","sex":"女"} =========JSON字符串转Java对象========= JSON.parseObject(str2, User.class) ==> User(name=zkk 1号, age=14, sex=女) =========Java对象转JSON对象========= (JSONObject) JSON.toJSON(user1) ==> {"sex":"女","name":"zkk 1号","age":14} =========JSON对象转Java对象========= JSON.toJavaObject(jsonObject, User.class) ==> User(name=zkk 1号, age=14, sex=女)

浙公网安备 33010602011771号