SpringBoot-Implementation of returning JSON data

  JSON  is the current mainstream front-end data transmission method, especially now that the front-end and back-end separation mode is prevailing, and the back-end returns JSON format data is even more mainstream. In the  Spring Boot  project, as long as you add a  web  dependency ( spring-boot-starter-web ), you can easily implement  JSON  conversion.

One, the default implementation

 Web  dependency has added  jackson-databind  as a  JSON  processor by default . We can return a piece of JSON without adding an additional  JSON  processor  . Example demonstration:

1. Create an entity class

public class User {

    private String username;

    @JsonIgnore
    private String password;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime register;

   // 省略 setter getter 方法
}
  • @JsonIgnore : Some properties in the java bean are ignored when json is serialized. That is, when json is generated, its labeled attributes are not generated.
  • @JsonFormat : Format the date type data into a string in the specified format.

2. Create Controller

In this  Contoller  , we initialize a  User object and then return it directly.

@Controller
public class UserController {

    @GetMapping("/user")
    @ResponseBody
    public User user(){
        User user = new User();
        user.setPassword("123456");
        user.setUsername("admin");
        user.setRegister(LocalDateTime.now());
        return user;
    }
}
  • To return data in JSON format, add @ResponseBody annotation to the method ,
  • If you don’t want to add @ResponseBody annotations to each method , you can use @RestController combined annotations instead of @Controller and @ ResponseBody

3. Start the service and test the results

Two, custom converter

In addition to jackson-databind , common JSON processors include  Gson  and  fastjson.

1. Use Gson

(1), add dependency

  Gson is an open source JSON parsing framework from Google . To use Gson , you need to remove the default jackson-databind first , and then add the Gson dependency. The code is as follows:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 移除jackson-databind 的依赖-->
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- 添加 GSON 依赖 -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
  • Spring Boot provides Gson 's automatic conversion class GsonHttpMessageConvertersConfiguration by default , so after the Gson dependency is successfully added, it can be used directly like jackson-databind .
  • But when  Gson  performs conversion, if you want to format the date data, you also need to customize the  HttpMessageConverter .

(2), custom HttpMessageConverter

@Configuration
public class GsonConfig {
    @Bean
    public HttpMessageConverter httpMessageConverter(){
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        GsonBuilder builder = new GsonBuilder();

        //反序列化 LocalDateTime
        builder.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) -> {
            String format = src.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            return new JsonPrimitive(format);
        });

        // 解析 Date类型
        builder.setDateFormat("yyyy-MM-dd HH:mm:ss");

        //解析时修饰符为protected的字段被过滤掉
        builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
        Gson gson = builder.create();
        converter.setGson(gson);
        return converter;
    }
}

(3), restart service access

2. Use fastjson

fastjson is an open source JSON parsing framework of Alibaba . It is currently the fastest open source framework for JSON parsing. The framework can also be integrated into Spring Boot . Unlike Gson , fastjson cannot be used immediately after the inheritance is completed. The developer needs to provide the corresponding HttpMessageConverter before it can be used. The steps to integrate fastjson are as follows

(1), add dependency

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!-- 移除jackson-databind 的依赖-->
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

(2), custom HttpMessageConverter

@Configuration
public class CustomerFastJsonConfig {

    @Bean
    public HttpMessageConverter httpMessageConverter(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setSerializerFeatures(
                SerializerFeature.WriteClassName,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.PrettyFormat,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty
        );
        converter.setFastJsonConfig(config);
        return converter;
    }

}
  • You can   exclude the serialization of an attribute by adding  @JSONField(serialize=false) annotation to the attribute, similar to the @JsonIgnore annotation in jackson 

(3), restart access

Guess you like

Origin blog.csdn.net/small_love/article/details/111725125