当前位置:网站首页>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 )
边栏推荐
- Thoughts on the compilation of Dr. Shuo's opening report
- Dimension disaster dimension disaster suspense
- How to build a customer-centric product blueprint: suggestions from the chief technology officer
- Leetcode 2119. number reversed twice
- 【Oauth2】五、OAuth2LoginAuthenticationFilter
- 算法--连续数列(Kotlin)
- Intercept the coordinate points (four point coordinates of the face frame) face image from the marked XML file and save it in the specified folder
- TDSQL-C Serverless:助力初创企业实现降本增效
- Comparison between SIGMOD function and softmax function
- Solution 5g technology helps build smart Parks
猜你喜欢

【着色器实现Overlay重新覆盖变装效果_Shader效果第九篇】

Re bet overseas: Alibaba, jd.com and SF again fight for "internal power"

天津市应急局与驻津央企签署协议深化应急联动机制建设

Team research and development from ants' foraging process (Reprint)

JSON数据传递参数&日期型参数传递

【C语言学习者必会的题目集锦1】巩固基础,稳步提高

《Kotlin系列》之MVVM架构封装(kotlin+mvvm)

HCIP第十一天比较(BGP的配置、发布)

Detailed relation extraction model casrel
![[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]
随机推荐
Photoshop(CC2020)未完
421. 数组中两个数的最大异或值
消息的订阅和发布
Using the geoprocessor tool
[oauth2] VIII. Configuration logic of oauth2 login -oauth2loginconfigurer and oauth2clientconfigurer
多线程使用不当导致的 OOM
See you tomorrow at the industrial session of cloud intelligence technology forum!
Niuke brush sql---2
Parent class reference to child class (parent class reference points to child class object)
[flower carving hands-on] interesting and fun music visualization series small project (13) -- organic rod column lamp
B+ tree (3) clustered index, secondary index -- MySQL from entry to proficiency (XV)
Dimension disaster dimension disaster suspense
Some practical operations of vector
[beauty of open source] nanomsg (2): req/rep mode
The last time I heard about eBay, or the last time
解决远程主机无法连接mysql数据库的问题
Sword finger offer (IX): abnormal jumping steps
Sword finger offer (VII): Fibonacci sequence
Team research and development from ants' foraging process (Reprint)
I. creation and constraint of MySQL table