Table of Contents
1. @RestController annotation
2. Jackson
1. Convert Object, List, Map to Json format
2. Jackson's configuration class
3. Fastjson
Fastjson configuration class
4. Encapsulate the returned data format
Home Java javaTutorial How does SpringBoot return Json data format

How does SpringBoot return Json data format

May 19, 2023 pm 11:49 PM
json springboot

    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 "";
    }
    Copy after login

    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>
    Copy after login

    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>
    Copy after login

    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和带参构造方法 */
    }
    Copy after login

    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"}
    
        }
    }
    Copy after login

    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 字段转成空字符串了。
    }
    Copy after login

    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.

    How does SpringBoot return Json data format

    Dependencies of fastjson

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.35</version>
    </dependency>
    Copy after login

    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);
        }
    }
    Copy after login

    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 方法
    }
    Copy after login

    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":"操作成功!"}
    
        }
    }
    Copy after login

    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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

    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.

    Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

    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

    What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

    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 tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

    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 Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

    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

    Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

    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

    How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

    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

    Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Nov 03, 2023 pm 03:44 PM

    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

    See all articles