使用jackson
导入jar包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10.6</version>
</dependency>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc-servlet.xml
<?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
https://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
">
<!--注解扫描-->
<context:component-scan base-package="com.starry.controller"></context:component-scan>
<!--json乱码问题配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="utf-8"></constructor-arg>
</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"></property>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
Controller
json格式输出java对象
@Controller
public class UserController {
@RequestMapping(value = "j1")
@ResponseBody
public String json1() throws JsonProcessingException {
User user = new User("繁星", 20, "男");
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(user);
return value;
}
}
@ResponseBody
: 不会走视图解析器,直接返回字符串
可在类上加注解@RestController
相当于@Controller
和@ResponseBody
输出结果
{"name":"繁星","age":20,"sex":"男"}
json格式输出集合
@RestController
public class UserController {
@RequestMapping(value = "j2")
public String json2() throws JsonProcessingException {
User user1 = new User("繁星1", 20, "男");
User user2 = new User("繁星2", 21, "男");
User user3 = new User("繁星3", 22, "男");
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
return new ObjectMapper().writeValueAsString(userList);
}
}
输出结果
[{"name":"繁星1","age":20,"sex":"男"},{"name":"繁星2","age":21,"sex":"男"},{"name":"繁星3","age":22,"sex":"男"}]
json格式输出时间
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//创建时间一个对象,java.util.Date
Date date = new Date();
//将对象解析成为json格式
String str = mapper.writeValueAsString(date);
return str;
}
输出结果为时间戳,Jackson 默认是会把时间转成timestamps
形式
取消timestamps
形式 , 自定义时间格式
@RequestMapping(value = "j3")
public String json3() throws JsonProcessingException {
Date date = new Date();
ObjectMapper objectMapper = new ObjectMapper();
//配置不使用时间戳
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//设置日期格式
objectMapper.setDateFormat(simpleDateFormat);
return objectMapper.writeValueAsString(date);
}
输出结果
"2021-04-08 11:19:46"
使用FastJson
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.37</version>
</dependency>
Controller
@RequestMapping(value = "j4")
public String json4() throws JsonProcessingException {
User user1 = new User("繁星1", 20, "男");
User user2 = new User("繁星2", 21, "男");
User user3 = new User("繁星3", 22, "男");
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
String userJosn = JSON.toJSONString(user1);
String userListJson = JSON.toJSONString(userList);
System.out.println("java对象转json字符串");
System.out.println(userJosn);
System.out.println("集合转json字符串");
System.out.println(userListJson);
User user = JSON.parseObject(userJosn, User.class);
List<User> userList1 = JSON.parseArray(userListJson,User.class);
System.out.println("json字符串转java对象");
System.out.println(user);
System.out.println("json字符串转集合");
for (User userOne : userList1) {
System.out.println(userOne);
}
return "testFastJson";
}
输出结果
java对象转json字符串
{"age":20,"name":"繁星1","sex":"男"}
集合转json字符串
[{"age":20,"name":"繁星1","sex":"男"},{"age":21,"name":"繁星2","sex":"男"},{"age":22,"name":"繁星3","sex":"男"}]
json字符串转java对象
User(name=繁星1, age=20, sex=男)
json字符串转集合
User(name=繁星1, age=20, sex=男)
User(name=繁星2, age=21, sex=男)
User(name=繁星3, age=22, sex=男)