SpringBoot 預設json解析器詳解和欄位序列化自定義

kenx發表於2021-08-04

前言

在我們開發專案API介面的時候,一些沒有資料的欄位會預設返回NULL,數字型別也會是NULL,這個時候前端希望字串能夠統一返回空字元,數字預設返回0,那我們就需要自定義json序列化處理

SpringBoot預設的json解析方案

我們知道在springboot中有預設的json解析器,Spring Boot 中預設使用的 Json 解析技術框架是 jackson。我們點開 pom.xml 中的 spring-boot-starter-web 依賴,可以看到一個 spring-boot-starter-json 依賴:

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-json</artifactId>
      <version>2.4.7</version>
      <scope>compile</scope>
    </dependency>

Spring Boot 中對依賴都做了很好的封裝,可以看到很多 spring-boot-starter-xxx 系列的依賴,這是 Spring Boot 的特點之一,不需要人為去引入很多相關的依賴了,starter-xxx 系列直接都包含了所必要的依賴,所以我們再次點進去上面這個 spring-boot-starter-json 依賴,可以看到:

 <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
      <version>2.11.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jsr310</artifactId>
      <version>2.11.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
      <version>2.11.4</version>
      <scope>compile</scope>
    </dependency>

我們在controller中返回json時候通過註解@ResponseBody就可以自動幫我們將服務端返回的物件序列化成json字串,在傳遞json body引數時候 通過在物件引數上@RequestBody註解就可以自動幫我們將前端傳過來的json字串反序列化成java物件

這些功能都是通過HttpMessageConverter這個訊息轉換工具類來實現的

SpringMVC自動配置了JacksonGson的HttpMessageConverter,SpringBoot對此做了自動化配置

JacksonHttpMessageConvertersConfiguration

org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(ObjectMapper.class)
	@ConditionalOnBean(ObjectMapper.class)
	@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
			havingValue = "jackson", matchIfMissing = true)
	static class MappingJackson2HttpMessageConverterConfiguration {

		@Bean
		@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class,
				ignoredType = {
						"org.springframework.hateoas.server.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
						"org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
			return new MappingJackson2HttpMessageConverter(objectMapper);
		}

	}

JacksonAutoConfiguration

org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration

@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(Jackson2ObjectMapperBuilder.class)
	static class JacksonObjectMapperConfiguration {

		@Bean
		@Primary
		@ConditionalOnMissingBean
		ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
			return builder.createXmlMapper(false).build();
		}

	}

Gson的自動化配置類

org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration

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

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

	}

自定義SprinBoot的JSON解析

日期格式解析

預設返回的是時間戳型別格式,但是時間戳會少一天需要在資料庫連線url上加上時區如:

spring.datasource.url=jdbc:p6spy:mysql://47.100.78.146:3306/mall?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&autoReconnect=true

  1. 使用@JsonFormat註解自定義格式
	@JsonFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

但是這種要對每個實體類中的日期欄位都需要新增此註解不夠靈活

  1. 全域性新增
    在配置檔案中直接新增spring.jackson.date-format=yyyy-MM-dd

NULL欄位不返回

  1. 在介面中如果不需要返回null欄位可以使用@JsonInclude註解
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private String title;

但是這種要對每個實體類中的欄位都需要新增此註解不夠靈活

  1. 全域性新增 在配置檔案中直接新增spring.jackson.default-property-inclusion=non_null

自定義欄位序列化

自定義null字串型別欄位返回空字元NullStringJsonSerializer序列化

public class NullStringJsonSerializer extends JsonSerializer {
    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o == null) {
            jsonGenerator.writeString("");
        }
    }
}

自定義null數字型別欄位返回0預設值NullIntegerJsonSerializer序列化

public class NullIntegerJsonSerializer extends JsonSerializer {
    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o == null) {
            jsonGenerator.writeNumber(0);
        }
    }
}

自定義浮點小數型別4舍5入保留2位小數DoubleJsonSerialize序列化

public class DoubleJsonSerialize extends JsonSerializer {
    private DecimalFormat df = new DecimalFormat("##.00");

    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value != null) {
            jsonGenerator.writeString(NumberUtil.roundStr(value.toString(), 2));
        }else{
            jsonGenerator.writeString("0.00");
        }

    }
}

自定義NullArrayJsonSerializer序列化

public class NullArrayJsonSerializer extends JsonSerializer {


    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if(o==null){
            jsonGenerator.writeStartArray();
        }else {
            jsonGenerator.writeObject(o);
        }
    }
}

自定義BeanSerializerModifier使用我們自己的序列化器進行bean序列化

public class MyBeanSerializerModifier extends BeanSerializerModifier {

    private JsonSerializer _nullArrayJsonSerializer = new NullArrayJsonSerializer();

    private JsonSerializer _nullStringJsonSerializer = new NullStringJsonSerializer();

    private JsonSerializer _nullIntegerJsonSerializer = new NullIntegerJsonSerializer();

    private JsonSerializer _doubleJsonSerializer = new DoubleJsonSerialize();

    @Override
    public List changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                 List beanProperties) { // 迴圈所有的beanPropertyWriter
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
            // 判斷欄位的型別,如果是array,list,set則註冊nullSerializer
            if (isArrayType(writer)) { //給writer註冊一個自己的nullSerializer
                writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
            }
            if (isStringType(writer)) {
                writer.assignNullSerializer(this.defaultNullStringJsonSerializer());
            }
            if (isIntegerType(writer)) {
                writer.assignNullSerializer(this.defaultNullIntegerJsonSerializer());
            }
            if (isDoubleType(writer)) {
                writer.assignSerializer(this.defaultDoubleJsonSerializer());
            }
        }
        return beanProperties;
    } // 判斷是什麼型別

    protected boolean isArrayType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
    }

    protected boolean isStringType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.equals(String.class);
    }

    protected boolean isIntegerType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.equals(Integer.class) || clazz.equals(int.class) || clazz.equals(Long.class);
    }

    protected boolean isDoubleType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.equals(Double.class) || clazz.equals(BigDecimal.class);
    }


    protected JsonSerializer defaultNullArrayJsonSerializer() {
        return _nullArrayJsonSerializer;
    }

    protected JsonSerializer defaultNullStringJsonSerializer() {
        return _nullStringJsonSerializer;
    }

    protected JsonSerializer defaultNullIntegerJsonSerializer() {
        return _nullIntegerJsonSerializer;
    }

    protected JsonSerializer defaultDoubleJsonSerializer() {
        return _doubleJsonSerializer;
    }
}

應用我們自己bean序列化使其生效 提供MappingJackson2HttpMessageConverter類
在配置類中提供MappingJackson2HttpMessageConverter類,使用ObjectMapper 做全域性的序列化

@Configuration
public class ClassJsonConfiguration {
    @Bean
    public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

        ObjectMapper mapper = converter.getObjectMapper();

        // 為mapper註冊一個帶有SerializerModifier的Factory,此modifier主要做的事情為:判斷序列化型別,根據型別指定為null時的值

        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));

        return converter;
    }
}

此類會代替SpringBoot預設的json解析方案。事實上,此類中起作用的是ObjectMapper 類,因此也可直接配置此類。

 @Bean
    public ObjectMapper om() {
        ObjectMapper mapper = new ObjectMapper();
        // 為mapper註冊一個帶有SerializerModifier的Factory,此modifier主要做的事情為:判斷序列化型別,根據型別指定為null時的值

        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
        return mapper;
    }

通過上面方式自定義序列化,還可以通過註解 @JsonSerialize序列化自定義如:

@Component
public class DoubleSerialize extends JsonSerializer<Double> {
 
    private DecimalFormat df = new DecimalFormat("##.00");  
 
    @Override
    public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
            throws IOException, JsonProcessingException {
        if(value != null) {
            gen.writeString(df.format(value));  
        }
    }
}

然後再需要使用欄位上面加上

 @JsonSerialize(using = DoubleJsonSerialize.class)
    private BigDecimal price;

配置檔案jackson詳細配置

  spring:
    jackson:
      # 設定屬性命名策略,對應jackson下PropertyNamingStrategy中的常量值,SNAKE_CASE-返回的json駝峰式轉下劃線,json body下劃線傳到後端自動轉駝峰式
      property-naming-strategy: SNAKE_CASE
      # 全域性設定@JsonFormat的格式pattern
      date-format: yyyy-MM-dd HH:mm:ss
      # 當地時區
      locale: zh
      # 設定全域性時區
      time-zone: GMT+8
      # 常用,全域性設定pojo或被@JsonInclude註解的屬性的序列化方式
      default-property-inclusion: NON_NULL #不為空的屬性才會序列化,具體屬性可看JsonInclude.Include
      # 常規預設,列舉類SerializationFeature中的列舉屬性為key,值為boolean設定jackson序列化特性,具體key請看SerializationFeature原始碼
      serialization:
        WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date轉換成timestamp
        FAIL_ON_EMPTY_BEANS: true # 物件為空時是否報錯,預設true
      # 列舉類DeserializationFeature中的列舉屬性為key,值為boolean設定jackson反序列化特性,具體key請看DeserializationFeature原始碼
      deserialization:
        # 常用,json中含pojo不存在屬性時是否失敗報錯,預設true
        FAIL_ON_UNKNOWN_PROPERTIES: false
      # 列舉類MapperFeature中的列舉屬性為key,值為boolean設定jackson ObjectMapper特性
      # ObjectMapper在jackson中負責json的讀寫、json與pojo的互轉、json tree的互轉,具體特性請看MapperFeature,常規預設即可
      mapper:
        # 使用getter取代setter探測屬性,如類中含getName()但不包含name屬性與setName(),傳輸的vo json格式模板中依舊含name屬性
        USE_GETTERS_AS_SETTERS: true #預設false
      # 列舉類JsonParser.Feature列舉類中的列舉屬性為key,值為boolean設定jackson JsonParser特性
      # JsonParser在jackson中負責json內容的讀取,具體特性請看JsonParser.Feature,一般無需設定預設即可
      parser:
        ALLOW_SINGLE_QUOTES: true # 是否允許出現單引號,預設false
      # 列舉類JsonGenerator.Feature列舉類中的列舉屬性為key,值為boolean設定jackson JsonGenerator特性,一般無需設定預設即可
      # JsonGenerator在jackson中負責編寫json內容,具體特性請看JsonGenerator.Feature
 

相關文章