Home > Java > Java Tutorial > body text

How does SpringBoot return Json data format

WBOY
Release: 2023-05-19 23:49:41
forward
1687 people have browsed it

    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:

    
        org.springframework.boot
        spring-boot-starter-json
        2.0.3.RELEASE
        compile
    
    Copy after login

    Click again on the spring- mentioned above boot-starter-json dependency, you can see the following code:

    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.6
        compile
    
    
        com.fasterxml.jackson.datatype
        jackson-datatype-jdk8
        2.9.6
        compile
    
    
        com.fasterxml.jackson.datatype
        jackson-datatype-jsr310
        2.9.6
        compile
    
    
        com.fasterxml.jackson.module
        jackson-module-parameter-names
        2.9.6
        compile
    
    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 getUserList() {
            List 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 getMap() {
            Map 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() {
                @Override
                public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                    jsonGenerator.writeString("");
                }
            });
            return objectMapper;
        }
    }
    
    // 修改一下上面返回 Map 的接口,将几个值改成 null 测试一下:
    
    @RequestMapping("/map")
    public Map getMap() {
        Map 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

    
        com.alibaba
        fastjson
        1.2.35
    
    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> 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 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 {
    
        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 getUser() {
            User user = new User(1, "倪升武", "123456");
            return new JsonResult<>(user);
            // {"code":"0","data":{"id":1,"password":"123456","username":"倪升武"},"msg":"操作成功!"}
    
        }
    
        @RequestMapping("/list")
        public JsonResult getUserList() {
            List 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 getMap() {
            Map 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!

    Related labels:
    source:yisu.com
    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
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!