How does SpringBoot return Json data format
1. @RestController annotation
Use the @RestController annotation in the Controller in Spring Boot to return data in JSON format.
@RestController
annotation includes @Controller and @ResponseBody annotations.@ResponseBody
Annotation is to convert the returned data structure into JSON format.
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { String value() default ""; }
2. Jackson
The default JSON parsing technology framework used in Spring Boot is Jackson.
Click on the spring-boot-starter-web dependency in pom.xml, you can see the spring-boot-starter-json dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> <version>2.0.3.RELEASE</version> <scope>compile</scope> </dependency>
Click again on the spring- mentioned above boot-starter-json dependency, you can see the following code:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-parameter-names</artifactId> <version>2.9.6</version> <scope>compile</scope> </dependency>
So far, you can know that the default JSON parsing framework used in Spring Boot is Jackson.
1. Convert Object, List, Map to Json format
Create entity class:
public class User { private Long id; private String username; private String password; /* 省略get、set和带参构造方法 */ }
Controller layer
import com.itcodai.course02.entity.User; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping("/json") public class JsonController { @RequestMapping("/user") public User getUser() { return new User(1, "倪升武", "123456"); //返回 {"id":1,"username":"倪升武","password":"123456"} } @RequestMapping("/list") public List<User> getUserList() { List<User> userList = new ArrayList<>(); User user1 = new User(1, "倪升武", "123456"); User user2 = new User(2, "达人课", "123456"); userList.add(user1); userList.add(user2); return userList; //返回 [{"id":1,"username":"倪升武","password":"123456"},{"id":2,"username":"达人课","password":"123456"}] } @RequestMapping("/map") public Map<String, Object> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", "123456"); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", "http://blog.csdn.net/eson_15"); map.put("粉丝数量", 4153); return map; //返回 {"作者信息":{"id":1,"username":"倪升武","password":"123456"},"CSDN地址":"http://blog.csdn.net/eson_15","粉丝数量":4153,"博客地址":"http://blog.itcodai.com"} } }
2. Jackson's configuration class
Convert all nulls to "" configuration when converting to JSON format
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.io.IOException; @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; } } // 修改一下上面返回 Map 的接口,将几个值改成 null 测试一下: @RequestMapping("/map") public Map<String, Object> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", null); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", null); map.put("粉丝数量", 4153); return map; // 返回 {"作者信息":{"id":1,"username":"倪升武","password":""},"CSDN地址":"","粉丝数量":4153,"博客地址":"http://blog.itcodai.com"} // 可以看到 Jackson 已经将所有 null 字段转成空字符串了。 }
3. Fastjson
Fastjson It is open sourced by Alibaba.
What are the differences between Jackson and fastjson?
From the perspective of expansion, fastjson is not as flexible as Jackson. From the perspective of speed or difficulty of getting started, fastjson can be considered, and it is also more convenient.
Dependencies of fastjson
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency>
Fastjson configuration class
When using fastjson, the handling of null is somewhat different from Jackson, and you need to inherit WebMvcConfigurationSupport class and then override the configureMessageConverters method.
In the method, we can choose the scenario to implement null conversion. The code is as follows:
import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @Configuration public class fastJsonConfig extends WebMvcConfigurationSupport { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd"); config.setSerializerFeatures( // 保留 Map 空的字段 SerializerFeature.WriteMapNullValue, // 将 String 类型的 null 转成"" SerializerFeature.WriteNullStringAsEmpty, // 将 Number 类型的 null 转成 0 SerializerFeature.WriteNullNumberAsZero, // 将 List 类型的 null 转成 [] SerializerFeature.WriteNullListAsEmpty, // 将 Boolean 类型的 null 转成 false SerializerFeature.WriteNullBooleanAsFalse, // 生成的JSON格式化 SerializerFeature.PrettyFormat, // 避免循环引用 SerializerFeature.DisableCircularReferenceDetect); converter.setFastJsonConfig(config); converter.setDefaultCharset(Charset.forName("UTF-8")); List<MediaType> mediaTypeList = new ArrayList<>(); // 解决中文乱码问题,相当于在 Controller 上的 @RequestMapping 中加了个属性 produces = "application/json" mediaTypeList.add(MediaType.APPLICATION_JSON); converter.setSupportedMediaTypes(mediaTypeList); converters.add(converter); } }
4. Encapsulate the returned data format
In addition to encapsulating the data, We often need to add some other information to the returned JSON, such as returning status code Code and Msg to the caller. The caller can make some logical judgments based on Code or Msg.
The attributes in the unified JSON structure include data, status code, and prompt information.
public class JsonResult<T> { private T data; private String code; private String msg; /** * 若没有数据返回,默认状态码为 0,提示信息为“操作成功!” */ public JsonResult() { this.code = "0"; this.msg = "操作成功!"; } /** * 若没有数据返回,可以人为指定状态码和提示信息 * @param code * @param msg */ public JsonResult(String code, String msg) { this.code = code; this.msg = msg; } /** * 有数据返回时,状态码为 0,默认提示信息为“操作成功!” * @param data */ public JsonResult(T data) { this.data = data; this.code = "0"; this.msg = "操作成功!"; } /** * 有数据返回,状态码为 0,人为指定提示信息 * @param data * @param msg */ public JsonResult(T data, String msg) { this.data = data; this.code = "0"; this.msg = msg; } // 省略 get 和 set 方法 }
Modify the return value type in Controller and test
@RestController @RequestMapping("/jsonresult") public class JsonResultController { @RequestMapping("/user") public JsonResult<User> getUser() { User user = new User(1, "倪升武", "123456"); return new JsonResult<>(user); // {"code":"0","data":{"id":1,"password":"123456","username":"倪升武"},"msg":"操作成功!"} } @RequestMapping("/list") public JsonResult<List> getUserList() { List<User> userList = new ArrayList<>(); User user1 = new User(1, "倪升武", "123456"); User user2 = new User(2, "达人课", "123456"); userList.add(user1); userList.add(user2); return new JsonResult<>(userList, "获取用户列表成功"); // {"code":"0","data":[{"id":1,"password":"123456","username":"倪升武"},{"id":2,"password":"123456","username":"达人课"}],"msg":"获取用户列表成功"} } @RequestMapping("/map") public JsonResult<Map> getMap() { Map<String, Object> map = new HashMap<>(3); User user = new User(1, "倪升武", null); map.put("作者信息", user); map.put("博客地址", "http://blog.itcodai.com"); map.put("CSDN地址", null); map.put("粉丝数量", 4153); return new JsonResult<>(map); // {"code":"0","data":{"作者信息":{"id":1,"password":"","username":"倪升武"},"CSDN地址":null,"粉丝数量":4153,"博客地址":"http://blog.itcodai.com"},"msg":"操作成功!"} } }
The above is the detailed content of How does SpringBoot return Json data format. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Using PHP's json_encode() function to convert an array or object into a JSON string and format the output can make it easier to transfer and exchange data between different platforms and languages. This article will introduce the basic usage of the json_encode() function and how to format and output a JSON string. 1. Basic usage of json_encode() function The basic syntax of json_encode() function is as follows: stringjson_encod
