springboot项目中jackson-序列化-处理 NULL教程
在项目中有事需要对值为NULL的对象中Field不做序列化输入配置方式如下:
[配置类型]:
源码包中的枚举类:
publicstaticenumInclude{ ALWAYS, NON_NULL, NON_ABSENT, NON_EMPTY, NON_DEFAULT, USE_DEFAULTS; privateInclude(){ } }
Include.Include.ALWAYS默认
Include.NON_DEFAULT属性为默认值不序列化
Include.NON_EMPTY属性为空(“”)或者为NULL都不序列化
Include.NON_NULL属性为NULL不序列化
方式一:全局配置,处理所有整个应用的实体对象
#对日期类型的转换配置 spring.jackson.date-format=yyyy-MM-ddHH:mm:ss #配置参数如下alwaysnon_absentnon_defaultnon_emptynon_nulluse_defaults spring.jackson.default-property-inclusion=non_null
方式二:在需要序列的话的实体类上加注解->[配置类型]所列
@JsonInclude(Include.NON_NULL)
方式三:配置类型
3.1自定义序列化实现类,可以作用在类上自定义json序列化需要实现StdSerializer
@JsonSerialize(using=ClientObjectSerialize.class) publicclassCreditBorrowerRepaymentRequestDto{ }
实现类:对字段类型转换,以及对值为null字段的过滤
publicclassClientObjectSerializeextendsJsonSerializer{ @Override publicvoidserialize(CreditBorrowerRepaymentRequestDtodto,JsonGeneratorjsonGenerator,SerializerProviderserializerProvider)throwsIOException,JsonProcessingException{ jsonGenerator.writeStartObject(); try{ Field[]fields=dto.getClass().getDeclaredFields(); for(Fieldfield:fields){ field.setAccessible(true); if(null==field.get(dto)){ continue; } jsonGenerator.writeFieldName(field.getName()); jsonGenerator.writeObject(field.get(dto)); } }catch(Exceptione){ e.printStackTrace(); } jsonGenerator.writeEndObject(); } }
3.2自定义序列化实现类,可以作用在实体对象字段上,对NULL值的处理,或者转换
@JsonSerialize(using=ClientStringSerialize.class) privateStringname; @JsonSerialize(using=ClientDtaeSerialize.class) privateDatedate; publicclassClientStringSerializeextendsJsonSerializer{ @Override publicvoidserialize(Stringstring,JsonGeneratorjsonGenerator,SerializerProviderserializerProvider)throwsIOException{ if(string==null){ jsonGenerator.writeString(string+"[NULL]"); }else{ jsonGenerator.writeString(string); } } } publicclassClientDtaeSerializeextendsJsonSerializer { @Override publicvoidserialize(DatecreateDate,JsonGeneratorjsonGenerator,SerializerProviderserializerProvider)throwsIOException{ jsonGenerator.writeString(newSimpleDateFormat("yyyy-MM-ddHH:mm:ss").format(createDate)); } }
实践总结:
一当全局配置了NULL字段过滤的配置,但有的实体对象需要序列化出NULL的字段值,如何处理?
答:
1.直接在对象上增加@JsonInclude(JsonInclude.Include.ALWAYS)类上的注解优先级比较高,会覆盖全局的配置
2.用自定义的类序列化注解(同上)
二直接在字段上加自定义序列化类会覆盖全局配置吗?
答:不会,有默认的publicclassNullSerializerextendsStdSerializer
补充知识:SpringBoot中Jackson返回null处理,字符串类型转空串,数组集合转[],对象转{}
SpringBoot返回Json数据中null值处理,将字符串类型null值转换为"",将集合数组类型null值转换为[],将原始数据类型null值转换为0,将布尔类型null值转换为false,将实体对象null值转换为{}。
1.自定义null值序列化处理器
importcom.fasterxml.jackson.core.JsonGenerator; importcom.fasterxml.jackson.databind.JsonSerializer; importcom.fasterxml.jackson.databind.SerializerProvider; importjava.io.IOException; /** *自定义null值序列化处理器 */ publicclassCustomizeNullJsonSerializer{ /** *处理数组集合类型的null值 */ publicstaticclassNullArrayJsonSerializerextendsJsonSerializer
2.序列化程序修改器
importcom.fasterxml.jackson.databind.BeanDescription; importcom.fasterxml.jackson.databind.SerializationConfig; importcom.fasterxml.jackson.databind.ser.BeanPropertyWriter; importcom.fasterxml.jackson.databind.ser.BeanSerializerModifier; importjava.util.Collection; importjava.util.List; /** **此modifier主要做的事情为: *1.当序列化类型为数组集合时,当值为null时,序列化成[] *2.String类型值序列化为"" * **/ publicclassMyBeanSerializerModifierextendsBeanSerializerModifier{ @Override publicListchangeProperties(SerializationConfigconfig, BeanDescriptionbeanDesc, List beanProperties){ //循环所有的beanPropertyWriter for(inti=0;i clazz=writer.getType().getRawClass(); returnclazz.isArray()||Collection.class.isAssignableFrom(clazz); } /** *是否是String */ privatebooleanisStringType(BeanPropertyWriterwriter){ Class>clazz=writer.getType().getRawClass(); returnCharSequence.class.isAssignableFrom(clazz)||Character.class.isAssignableFrom(clazz); } /** *是否是数值类型 */ privatebooleanisNumberType(BeanPropertyWriterwriter){ Class>clazz=writer.getType().getRawClass(); returnNumber.class.isAssignableFrom(clazz); } /** *是否是boolean */ privatebooleanisBooleanType(BeanPropertyWriterwriter){ Class>clazz=writer.getType().getRawClass(); returnclazz.equals(Boolean.class); } }
3.配置Jackson实体
importcom.fasterxml.jackson.databind.ObjectMapper; importcom.fasterxml.jackson.databind.SerializerProvider; importorg.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; importorg.springframework.context.annotation.Bean; importorg.springframework.context.annotation.Configuration; importorg.springframework.context.annotation.Primary; importorg.springframework.http.converter.json.Jackson2ObjectMapperBuilder; /** *配置Jackson实体 */ @Configuration publicclassJacksonConfig{ @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) publicObjectMapperjacksonObjectMapper(Jackson2ObjectMapperBuilderbuilder){ ObjectMapperobjectMapper=builder.createXmlMapper(false).build(); /**为objectMapper注册一个带有SerializerModifier的Factory*/ objectMapper.setSerializerFactory(objectMapper.getSerializerFactory() .withSerializerModifier(newMyBeanSerializerModifier())); SerializerProviderserializerProvider=objectMapper.getSerializerProvider(); serializerProvider.setNullValueSerializer(newCustomizeNullJsonSerializer .NullObjectJsonSerializer()); returnobjectMapper; } }
以上这篇springboot项目中jackson-序列化-处理NULL教程就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。