springboot项⽬中jackson-序列化-处理NULL教程
在项⽬中有事需要对值为NULL的对象中Field不做序列化输⼊配置⽅式如下:
[配置类型]:
源码包中的枚举类:
public static enum Include {
ALWAYS,
NON_NULL,
NON_ABSENT,
NON_EMPTY,
NON_DEFAULT,
USE_DEFAULTS;
private Include() {
}
}
Include.Include.ALWAYS 默认
Include.NON_DEFAULT 属性为默认值不序列化
Include.NON_EMPTY 属性为空(“”)或者为 NULL 都不序列化
Include.NON_NULL 属性为NULL 不序列化
⽅式⼀:全局配置,处理所有整个应⽤的实体对象
#对⽇期类型的转换配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
# 配置参数如下 always non_absent non_default non_empty non_null use_defaults
spring.jackson.default-property-inclusion=non_null
⽅式⼆:在需要序列的话的实体类上加注解 ->[配置类型]所列
@JsonInclude(Include.NON_NULL)
⽅式三:配置类型
3.1⾃定义序列化实现类,可以作⽤在类上⾃定义json序列化需要实现StdSerializer<T>或者JsonSerializer<T>
@JsonSerialize(using = ClientObjectSerialize.class)
public class CreditBorrowerRepaymentRequestDto{
}
实现类:对字段类型转换,以及对值为null字段的过滤
public class ClientObjectSerialize extends JsonSerializer<CreditBorrowerRepaymentRequestDto>{
@Override
public void serialize(CreditBorrowerRepaymentRequestDto dto, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeStartObject();
try {
Field[] fields = Class().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(null == (dto)){
continue;
}
jsonGenerator.Name());
jsonGenerator.(dto));
}
} catch (Exception e) {
e.printStackTrace();
}
jsonGenerator.writeEndObject();
}
}
3.2⾃定义序列化实现类,可以作⽤在实体对象字段上,对NULL值的处理,或者转换
@JsonSerialize(using = ClientStringSerialize.class)
private String name;
@JsonSerialize(using = ClientDtaeSerialize.class)
private Date date;
public class ClientStringSerialize extends JsonSerializer<String> {
@Override
public void serialize(String string, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if(string == null){
jsonGenerator.writeString(string + "[NULL]");
}else{
jsonGenerator.writeString(string);
}
}
}
public class ClientDtaeSerialize extends JsonSerializer<Date> {
@Override
public void serialize(Date createDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(createDate));
}
}
实践总结:
⼀当全局配置了NULL字段过滤的配置,但有的实体对象需要序列化出NULL的字段值,如何处理?
答:
1. 直接在对象上增加 @JsonInclude(JsonInclude.Include.ALWAYS) 类上的注解优先级⽐较⾼,会覆盖全局的配置
2.⽤⾃定义的类序列化注解(同上)
⼆直接在字段上加⾃定义序列化类会覆盖全局配置吗?
答:不会,有默认的 public class NullSerializer extends StdSerializer<Object> 来处理,当值不为Null的时候才会执⾏⾃定义字段上的序列化注解实现类
补充知识:SpringBoot中Jackson返回null处理,字符串类型转空串,数组集合转[],对象转{}
SpringBoot返回Json数据中null值处理,将字符串类型null值转换为"",将集合数组类型null值转换为[],将原始数据类型null值转换为0,将布尔类型null值转换为false,将实体对象null值转换为{}。
1.⾃定义null值序列化处理器
import com.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
springboot和过滤器/**
* ⾃定义null值序列化处理器
*/
public class CustomizeNullJsonSerializer {
/**
* 处理数组集合类型的null值
*/
public static class NullArrayJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeEndArray();
}
}
/**
* 处理字符串类型的null值
*/
public static class NullStringJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
}
/**
* 处理数值类型的null值
*/
public static class NullNumberJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(0);
}
}
/**
* 处理boolean类型的null值
*/
public static class NullBooleanJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeBoolean(false);
}
}
/**
* 处理实体对象类型的null值
*/
public static class NullObjectJsonSerializer extends JsonSerializer<Object> {
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeEndObject();
}
}
}
2.序列化程序修改器
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import java.util.Collection;
import java.util.List;
/**
* <pre>
* 此modifier主要做的事情为:
* 1.当序列化类型为数组集合时,当值为null时,序列化成[]
* 2.String类型值序列化为""
*
* </pre>
*/
public class MyBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
/
/ 循环所有的beanPropertyWriter
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = (i);
// 判断字段的类型,如果是数组或集合则注册nullSerializer
if (isArrayType(writer)) {
// 给writer注册⼀个⾃⼰的nullSerializer
writer.assignNullSerializer(new CustomizeNullJsonSerializer.NullArrayJsonSerializer());
}
if (isStringType(writer)) {
writer.assignNullSerializer(new CustomizeNullJsonSerializer.NullStringJsonSerializer());
}
}
return beanProperties;
}
/**
* 是否是数组
*/
private boolean isArrayType(BeanPropertyWriter writer) {
Class<?> clazz = Type().getRawClass();
return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
}
/**
* 是否是String
*/
private boolean isStringType(BeanPropertyWriter writer) {
Class<?> clazz = Type().getRawClass();
return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz); }
/**
* 是否是数值类型
*/
private boolean isNumberType(BeanPropertyWriter writer) {
Class<?> clazz = Type().getRawClass();
return Number.class.isAssignableFrom(clazz);
}
/**
* 是否是boolean
*/
private boolean isBooleanType(BeanPropertyWriter writer) {
Class<?> clazz = Type().getRawClass();
return clazz.equals(Boolean.class);
}
}
3.配置Jackson实体
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.dition.ConditionalOnMissingBean;
import t.annotation.Bean;
import t.annotation.Configuration;
import t.annotation.Primary;
import org.verter.json.Jackson2ObjectMapperBuilder;
/**
* 配置Jackson实体
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = ateXmlMapper(false).build();
/** 为objectMapper注册⼀个带有SerializerModifier的Factory */
objectMapper.SerializerFactory()
.withSerializerModifier(new MyBeanSerializerModifier()));
SerializerProvider serializerProvider = SerializerProvider();
serializerProvider.setNullValueSerializer(new CustomizeNullJsonSerializer
.NullObjectJsonSerializer());
return objectMapper;
}
}
以上这篇springboot项⽬中jackson-序列化-处理 NULL教程就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论