Spring boot 默認是jackson
相關屬性可以通過代碼配置,也可以通過spring.jackson.default-property-inclusion=non_null
Springboot的配置文件進行配置
@Configuration
public class JacksonConfig
{
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
// 通過該方法對mapper對象進行設置,所有序列化的對象都將按改規則進行系列化
// Include.Include.ALWAYS 默認
// Include.NON_DEFAULT 屬性爲默認值不序列化
// Include.NON_EMPTY 屬性爲 空("") 或者爲 NULL 都不序列化,則返回的json是沒有這個字段的。這樣對移動端會更省流量
// Include.NON_NULL 屬性爲NULL 不序列化,就是爲null的字段不參加序列化
//objectMapper.setSerializationInclusion(Include.NON_EMPTY);
// 字段保留,將null值轉爲""
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
{
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException
{
jsonGenerator.writeString("");
}
});
return objectMapper;
}
}