当前位置:网站首页>JSON data returned by controller
JSON data returned by controller
2022-07-26 13:40:00 【starriesWEB】
Use jackson
Import jar package
<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 ">
<!-- Annotation scan -->
<context:component-scan base-package="com.starry.controller"></context:component-scan>
<!--json Garbled problem configuration -->
<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>
<!-- view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!-- Prefix -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- suffix -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Entity class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
Controller
json Format output java object
@Controller
public class UserController {
@RequestMapping(value = "j1")
@ResponseBody
public String json1() throws JsonProcessingException {
User user = new User(" clusters of stars ", 20, " male ");
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(user);
return value;
}
}
@ResponseBody : Don't go to view parser , Return string directly
You can annotate the class @RestController amount to @Controller and @ResponseBody
Output results
{
"name":" clusters of stars ","age":20,"sex":" male "}
json Format output set
@RestController
public class UserController {
@RequestMapping(value = "j2")
public String json2() throws JsonProcessingException {
User user1 = new User(" clusters of stars 1", 20, " male ");
User user2 = new User(" clusters of stars 2", 21, " male ");
User user3 = new User(" clusters of stars 3", 22, " male ");
List<User> userList = new ArrayList<User>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
return new ObjectMapper().writeValueAsString(userList);
}
}
Output results
[{
"name":" clusters of stars 1","age":20,"sex":" male "},{
"name":" clusters of stars 2","age":21,"sex":" male "},{
"name":" clusters of stars 3","age":22,"sex":" male "}]
json Format output time
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// Create time an object ,java.util.Date
Date date = new Date();
// Resolve the object to json Format
String str = mapper.writeValueAsString(date);
return str;
}
The output result is timestamp ,Jackson The default is to change the time to timestamps form
Cancel timestamps form , Customize the time format
@RequestMapping(value = "j3")
public String json3() throws JsonProcessingException {
Date date = new Date();
ObjectMapper objectMapper = new ObjectMapper();
// Configure not to use timestamp
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
// Customize the date format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Set the date format
objectMapper.setDateFormat(simpleDateFormat);
return objectMapper.writeValueAsString(date);
}
Output results
"2021-04-08 11:19:46"
Use FastJson
Import dependence
<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(" clusters of stars 1", 20, " male ");
User user2 = new User(" clusters of stars 2", 21, " male ");
User user3 = new User(" clusters of stars 3", 22, " male ");
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 Object turn json character string ");
System.out.println(userJosn);
System.out.println(" Collective transfer json character string ");
System.out.println(userListJson);
User user = JSON.parseObject(userJosn, User.class);
List<User> userList1 = JSON.parseArray(userListJson,User.class);
System.out.println("json String rotation java object ");
System.out.println(user);
System.out.println("json String conversion ");
for (User userOne : userList1) {
System.out.println(userOne);
}
return "testFastJson";
}
Output results
java Object turn json character string
{
"age":20,"name":" clusters of stars 1","sex":" male "}
Collective transfer json character string
[{
"age":20,"name":" clusters of stars 1","sex":" male "},{
"age":21,"name":" clusters of stars 2","sex":" male "},{
"age":22,"name":" clusters of stars 3","sex":" male "}]
json String rotation java object
User(name= clusters of stars 1, age=20, sex= male )
json String conversion
User(name= clusters of stars 1, age=20, sex= male )
User(name= clusters of stars 2, age=21, sex= male )
User(name= clusters of stars 3, age=22, sex= male )
边栏推荐
- File upload and download performance test based on the locust framework
- The use of asynchronous thread pool in development
- Golang port scanning design
- 如何构建以客户为中心的产品蓝图:来自首席技术官的建议
- LeetCode 1523. 在区间范围内统计奇数数目
- One stroke problem (Chinese postman problem)
- Photoshop(CC2020)未完
- Comparator (interface between comparable and comparator)
- Tianjin emergency response Bureau and central enterprises in Tianjin signed an agreement to deepen the construction of emergency linkage mechanism
- Sword finger offer (x): rectangular coverage
猜你喜欢

Zhou Wei: look for non consensual investment opportunities to accompany the founding team that delays satisfaction

Hcip day 11 comparison (BGP configuration and release)

This article explains the FS file module and path module in nodejs in detail
![[shaders realize overlay to re cover cross dressing effect _shader effect Chapter 9]](/img/f3/48ca9e1e8889afc0993084d6416575.png)
[shaders realize overlay to re cover cross dressing effect _shader effect Chapter 9]

How to write the introduction of GIS method journals and papers?

Analysis on the current situation and optimization strategy of customer experience management in banking industry
![[upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication](/img/d4/c677de31f73a0e0a4b8b10b91e984a.png)
[upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication

Activity.onStop() 延迟10秒?精彩绝伦的排查历程

Hcip day 12 notes sorting (BGP Federation, routing rules)
![[dark horse morning post] many apps under bytek have been taken off the shelves; The leakage of deoxidizer in three squirrels caused pregnant women to eat by mistake; CBA claimed 406million yuan from](/img/f6/03e39799db36c33a58127359aa2794.png)
[dark horse morning post] many apps under bytek have been taken off the shelves; The leakage of deoxidizer in three squirrels caused pregnant women to eat by mistake; CBA claimed 406million yuan from
随机推荐
Pytorch学习笔记(一)安装与常用函数的使用
File upload and download performance test based on the locust framework
[shaders realize overlay to re cover cross dressing effect _shader effect Chapter 9]
[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer
421. Maximum XOR value of two numbers in the array
Outline design specification
ROS2学习(1)ROS2简述
重押海外:阿里、京东、顺丰再拼“内力”
Solve the problem that the remote host cannot connect to the MySQL database
Unicorn, valued at $1.5 billion, was suddenly laid off, and another track was cold?
Codeforces round 810 (Div. 2) [competition record]
飞盘,2022年“黑红”顶流
Jenkins 中 shell 脚本执行失败却不自行退出
I. creation and constraint of MySQL table
Can I take your subdomain? Exploring Same-Site Attacks in the Modern Web
Exploration on cache design optimization of community like business
SuperMap iclient for leaflet loads Gauss Kruger projection three-dimensional zonation CGCS2000 geodetic coordinate system WMTs service
B+ tree selection index (2) -- MySQL from entry to proficiency (23)
[collection of topics that C language learners must know 1] consolidate the foundation and steadily improve
白帽子揭秘:互联网千亿黑产吓退马斯克