智慧屏 安装 app如何提升家庭娱乐与教育体验的关键工具
720
2023-03-27
springboot项目中jackson
在项目中有事需要对值为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
@JsonSerialize(using = ClientObjectSerialize.class)
public class CreditBorrowerRepaymentRequestDto{
}
实现类:对字段类型转换,以及对值为null字段的过滤
public class ClientObjectSerialize extends JsonSerializer
@Override
public void serialize(CreditBorrowerRepaymentRequestDto dto, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeStartObject();
try {
Field[] fields = dto.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(null == field.get(dto)){
continue;
}
jsonGenerator.writeFieldName(field.getName());
jsonGenerator.writeObject(field.get(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
@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
@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
补充知识:SpringBoot中Jackson返回null处理,字符串类型转空串,数组集合转[],对象转{}
SpringBoot返回Json数据中null值处理,将字符串类型null值转换为"",将集合数组类型null值转换为[],将原始数据类型null值转换为0,将布尔类型null值转换为false,将实体对象null值转换为{}。
1.自定义null值序列化处理器
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
/**
* 自定义null值序列化处理器
*/
public class CustomizeNullJsonSerializer {
/**
* 处理数组集合类型的null值
*/
public static class NullArrayJsonSerializer extends JsonSerializer
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartArray();
jsonGenerator.writeEndArray();
}
}
/**
* 处理字符串类型的null值
*/
public static class NullStringJsonSerializer extends JsonSerializer
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
}
/**
* 处理数值类型的null值
*/
public static class NullNumberJsonSerializer extends JsonSerializer
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeNumber(0);
}
}
/**
* 处理boolean类型的null值
*/
public static class NullBooleanJsonSerializer extends JsonSerializer
@Override
public void serialize(Object value, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeBoolean(false);
}
}
/**
* 处理实体对象类型的null值
*/
public static class NullObjectJsonSerializer extends JsonSerializer
@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;
/**
*
* 此modifier主要做的事情为:
* 1.当序列化类型为数组集合时,当值为null时,序列化成[]
* 2.String类型值序列化为""
*
*
*/
public class MyBeanSerializerModifier extends BeanSerializerModifier {
@Override
public List
BeanDescription beanDesc,
List
// 循环所有的beanPropertyWriter
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = beanProperties.get(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 = writer.getType().getRawClass();
return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
}
/**
* 是否是String
*/
private boolean isStringType(BeanPropertyWriter writer) {
Class> clazz = writer.getType().getRawClass();
return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
}
/**
* 是否是数值类型
*/
private boolean isNumberType(BeanPropertyWriter writer) {
Class> clazz = writer.getType().getRawClass();
return Number.class.isAssignableFrom(clazz);
}
/**
* 是否是boolean
*/
private boolean isBooleanType(BeanPropertyWriter writer) {
Class> clazz = writer.getType().getRawClass();
return clazz.equals(Boolean.class);
}
}
3.配置Jackson实体
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
/**
* 配置Jackson实体
*/
@Configuration
public class JacksonConfig {
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
/** 为objectMapper注册一个带有SerializerModifier的Factory */
objectMapper.setSerializerFactory(objectMapper.getSerializerFactory()
.withSerializerModifier(new MyBeanSerializerModifier()));
SerializerProvider serializerProvider = objectMapper.getSerializerProvider();
serializerProvider.setNullValueSerializer(new CustomizeNullJsonSerializer
.NullObjectJsonSerializer());
return objectMapper;
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~