当前位置:网站首页>Controller返回JSON数据
Controller返回JSON数据
2022-07-26 10:24:00 【starriesWEB】
使用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=男)
边栏推荐
- Uniapp common error [wxml file compilation error]./pages/home/home Wxml and using MySQL front provided by phpstudy to establish an independent MySQL database and a detailed tutorial for independent da
- The CLOB field cannot be converted when querying Damon database
- What will the new Fuzhou Xiamen railway bring to Fujian coastal areas?
- 数通基础-Telnet远程管理设备
- [Halcon vision] image filtering
- Cause: couldn‘t make a guess for 解决方法
- 函数模板与同名的非模板函数不可以重载(重载的定义)
- Mlx90640 infrared thermal imager temperature sensor module development notes (6)
- 【Halcon视觉】仿射变换
- Common errors when starting projects in uniapp ---appid
猜你喜欢
随机推荐
2022/07/25------字符串的排列
On the compilation of student management system of C language course (simple version)
数据库的复习--1.概述
Under win10 64 bit, matlab fails to configure notebook
Deduct daily question 838 of a certain day
Nacos custom service change subscription
[Halcon vision] polar coordinate transformation
【Halcon视觉】阈值分割
【Halcon视觉】形态学腐蚀
Learning about tensorflow (II)
Learning about opencv (3)
【有奖提问】向图灵奖得主、贝叶斯网络之父 Judea Pearl 提问啦
抓包工具fiddler和wireshark对比
利用原生js实现自定义滚动条(可点击到达,拖动到达)
【C#语言】具名类型和匿名类型
The CLOB field cannot be converted when querying Damon database
[Halcon vision] morphological corrosion
String null to empty string (what does empty string mean)
数通基础-Telnet远程管理设备
Prevent XSS attacks








