Three schemes for parsing JSON data in Spring Boot

1 Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight data exchange format. Easy for humans to read and write. It is also easy for machines to parse and generate. JSON is a sequence of tokens. This set of tokens contains six constructed characters, strings, numbers, and three literal names. JSON is a serialized object or array.

2 Spring Boot default JSON parsing

When we add the spring-boot-starter-web dependency in the Spring Boot project, Jackson is provided by default for parsing Json

2.1 Example of use

Create an entity class

@Component
public class User {
    
    
  private long id;
  private String username;
  private Date birthday;

  public long getId() {
    
    
    return id;
  }

  public void setId(long id) {
    
    
    this.id = id;
  }

  public String getUsername() {
    
    
    return username;
  }

  public void setUsername(String username) {
    
    
    this.username = username;
  }

  public Date getBirthday() {
    
    
    return birthday;
  }

  public void setBirthday(Date birthday) {
    
    
    this.birthday = birthday;
  }
}

Create a Controller class for page access:

@RestController
public class ShowController {
    
    
  @GetMapping("/show")
  public List<User> show(){
    
    
    List<User> users=new ArrayList<User>();
    for (int i = 0; i < 5; i++) {
    
    
      User user=new User();
      user.setId(i);
      user.setUsername("张三"+i);
      user.setBirthday(new Date());
      users.add(user);

    }
    return  users;
  }
}

Start the project, visit the browser, and you can see that the data in JSON format is returned by default. You can see that the
insert image description here
Date type data above requires us to customize the format. Adding the JsonFormat annotation to the date attribute in the entity class can achieve:

  @JsonFormat(pattern = "YYYY-MM-dd")
  private Date birthday;

Restart the project after modification, browser access:
insert image description here
But when many classes need to configure custom formats, you need to add multiple annotations, which is troublesome and not conducive to later maintenance. So we need to modify the global JSON format.

The following takes modifying Date type data as an example:

2.2 Modify the global JSON format of specific data

The parsing of JSON is inseparable from HttpMessageConvert. HttpMessageConvert is a message conversion tool with two main functions:

  1. Serialize the object returned by the server into a JSON string
  2. Deserialize the JSON string from the front end into a Java object

Jackson and GsonHttpMessageConverter are configured by default in SpringMVC, which is automatically configured in Spring Boot, which is mainly implemented by the following two classes:

org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration

The source code of JacksonHttpMessageConvertersConfiguration is as follows:

@Configuration(
  proxyBeanMethods = false
)
class JacksonHttpMessageConvertersConfiguration {
    
    
  JacksonHttpMessageConvertersConfiguration() {
    
    
  }

  @Configuration(
    proxyBeanMethods = false
  )
  @ConditionalOnClass({
    
    XmlMapper.class})
  @ConditionalOnBean({
    
    Jackson2ObjectMapperBuilder.class})
  protected static class MappingJackson2XmlHttpMessageConverterConfiguration {
    
    
    protected MappingJackson2XmlHttpMessageConverterConfiguration() {
    
    
    }

    @Bean
    @ConditionalOnMissingBean
    public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) {
    
    
      return new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build());
    }
  }
//配置类注解
  @Configuration(
    proxyBeanMethods = false
  )
  /*
  *下面几个是条件注解,当添加了Jackson依赖,就有了ObjectMapper.class和属性,后面的配置就会生效
  */
  @ConditionalOnClass({
    
    ObjectMapper.class})
  @ConditionalOnBean({
    
    ObjectMapper.class})
  @ConditionalOnProperty(
    name = {
    
    "spring.http.converters.preferred-json-mapper"},
    havingValue = "jackson",
    matchIfMissing = true
  )

  static class MappingJackson2HttpMessageConverterConfiguration {
    
    
    MappingJackson2HttpMessageConverterConfiguration() {
    
    
    }

/*
*@ConditionalOnMissingBean的意思就是如果我们没有配置这个Bean,就自动创建一个默认的,当我们配置了就使用我们配置的Bean,不再创建
*/

    @Bean
    @ConditionalOnMissingBean(
      value = {
    
    MappingJackson2HttpMessageConverter.class},
      ignoredType = {
    
    "org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter"}
    )
    /*
    *MappingJackson2HttpMessageConverter就是Jackson的消息转换工具类
    */
    MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
    
    
    /*
    *JSON中序列化对象主要用ObjectMapper工具类
    */
      return new MappingJackson2HttpMessageConverter(objectMapper);
    }
  }
}

By looking at the source code above, we can know that we can modify the global format of the generated JSON in the following two ways:

2.2.1 Custom MappingJackson2HttpMessageConverter

Create a MappingJackson2HttpMessageConverter by yourself to replace the one that comes with the project in JacksonHttpMessageConvertersConfiguration.

Example:
In the project created above, first delete the JsonFormat annotation, and then create a new configuration class with the following content:

@Configuration
public class WebMVCConfig {
    
    
  @Bean
  MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(){
    
    
    MappingJackson2HttpMessageConverter converter=new MappingJackson2HttpMessageConverter();
    ObjectMapper om=new ObjectMapper();
    om.setDateFormat(new SimpleDateFormat("YYYY/MM/dd"));
    converter.setObjectMapper(om);
    return converter;
  }
}

2.2.2 Custom ObjectMapper

Through the above class, we can see that the main function of the class is ObjectMapping. The above JacksonHttpMessageConvertersConfiguration can see that ObjectMapping is directly injected. It is provided in the configuration class JacksonAutoConfiguration .
insert image description here
Modify the WebMVCConfig class as follows:

@Configuration
public class WebMVCConfig {
    
    
  @Bean
  ObjectMapper objectMapper(){
    
    
    ObjectMapper om=new ObjectMapper();
    om.setDateFormat(new SimpleDateFormat("YYYY/MM/DD"));
    return om;
  }

}

Both ways are possible, browser access:
insert image description here

3 Processing JSON with Gson

3.1 Example of use

To modify based on the project created above, first remove the spring-boot-starter-json dependency. Then add gson dependency:
insert image description here
Then comment or delete the jackson part of the configuration class and some imported jackson packages, and then start the project.
insert image description here
You can see that the date format is Gson's default. need to be modified

3.2 Modify the global JSON format for specific data

Part of the source code of GsonHttpMessageConvertersConfiguration is as follows:

  @Configuration(
    proxyBeanMethods = false
  )
  @ConditionalOnBean({
    
    Gson.class})
  @Conditional({
    
    GsonHttpMessageConvertersConfiguration.PreferGsonOrJacksonAndJsonbUnavailableCondition.class})
  static class GsonHttpMessageConverterConfiguration {
    
    
    GsonHttpMessageConverterConfiguration() {
    
    
    }

    @Bean
    @ConditionalOnMissingBean
    GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
    
    
      GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
      converter.setGson(gson);
      return converter;
    }

It can be seen that it is similar to Jackson, so it can be modified according to Jackson

3.2.1 Customize GsonHttpMessageConverter

@Configuration
public class WebMVCConfig {
    
    
    @Bean
      GsonHttpMessageConverter gsonHttpMessageConverter(){
    
    
      GsonHttpMessageConverter converter=new GsonHttpMessageConverter();
      converter.setGson(new GsonBuilder().setDateFormat("YYYY-MM-DD").create());
      return converter;
       }
 }

3.2.2 Custom Gson object

The above configuration mainly uses the Gson object, which is created for us in the GsonAutoConfiguration class when we have no configuration. Then use it in GsonHttpMessageConverter. We can also create a Gson object ourselves:

@Configuration
public class WebMVCConfig {
    
    

       @Bean
  Gson gson(){
    
    
   return new GsonBuilder().setDateFormat("YYYY-MM-DD").create();
       }

}

Both ways are possible, browser access:
insert image description here

4 Processing JSON with FastJson

4.1 Example of use

Based on the project created above, remove the Jackson dependency and add the FastJson dependency:
insert image description here
Because Spring Boot does not provide related automatic configuration classes, we need to manually create the FastJson message conversion tool class:

@Configuration
public class WebMVCConfig {
    
    
  @Bean
  FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
    
    
    FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
    return converter;
  }
  }

Start the project, browser access:
insert image description here
you can see that the date format has changed to FastJson format. Modifications are required.

4.2 Modify the global JSON format for specific data

FastJson is directly modified in the FastJsonHttpMessageConverter class to create a new FastJsonConfig object. At this time, the encoding needs to be set, otherwise garbled characters will appear:

@Configuration
public class WebMVCConfig {
    
    
  @Bean
  FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
    
    
    FastJsonHttpMessageConverter converter=new FastJsonHttpMessageConverter();
    FastJsonConfig config=new FastJsonConfig();
    // 处理中文乱码问题
    List<MediaType> fastMediaTypes = new ArrayList<>();
    fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    converter.setSupportedMediaTypes(fastMediaTypes);
    //设置日期格式
    config.setDateFormat("YYYY-MM-DD");
    converter.setFastJsonConfig(config);
    return converter;
  }
} 

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/132241530