SpringBootJackson配置项说明及其⾃定义序列化器
springboot之jackson的两种配置⽅式
SpringBoot对于Jackson的配置(通过l)
配置属性说明:
spring.jackson.date-format指定⽇期格式,⽐如yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名
spring.jackson.deserialization是否开启Jackson的反序列化
ator是否开启json的generators.
spring.jackson.joda-date-time-format指定Joda date/time的格式,⽐如yyyy-MM-ddHH:mm:ss). 如果没有配置的话,dateformat会作为backup
spring.jackson.locale指定json使⽤的Locale.
spring.jackson.mapper是否开启Jackson通⽤的特性.
spring.jackson.parser是否开启jackson的parser特性.
spring.jackson.property-naming-strategy指定PropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy⼦类的全限定类名.
spring.jackson.serialization是否开启jackson的序列化.
spring.jackson.serialization-inclusion指定序列化时属性的inclusion⽅式,具体查看JsonInclude.Include枚举.
spring.jackson.time-zone指定⽇期格式化时区,⽐如America/Los_Angeles或者GMT+10.
常⽤配置:
spring:
jackson:
#⽇期格式化
date-format: yyyy-MM-dd HH:mm:ss
serialization:
#格式化输出
indent_output: true
#忽略⽆法转换的对象
fail_on_empty_beans: false
#设置空如何序列化
defaultPropertyInclusion: NON_EMPTY
deserialization:
#允许对象忽略json中不存在的属性
fail_on_unknown_properties: false
parser:
spring怎么读取配置
#允许出现特殊字符和转义符
allow_unquoted_control_chars: true
#允许出现单引号
allow_single_quotes: true
⽅式⼆:⾃定义序列化器
默认对Null的处理
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
{
ObjectMapper objectMapper = ateXmlMapper(false).build();
// 通过该⽅法对mapper对象进⾏设置,所有序列化的对象都将按改规则进⾏系列化
// Include.Include.ALWAYS 默认
// Include.NON_DEFAULT 属性为默认值不序列化
// Include.NON_EMPTY 属性为空("")或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
// Include.NON_NULL 属性为NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// 允许出现特殊字符和转义符
// 允许出现单引号
// 字段保留,将null值转为""
{
@Override
public void serialize(Object o, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException
{
jsonGenerator.writeString("");
}
});
return objectMapper;
}
⾃定义对Map、List、String、Boolean、Integer、Object的处理
1. ⾃定义null值序列化处理器*
import com.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<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();
}
}
}
3. 序列化程序修改器*
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时,序列化成[]
* 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 serializerProvider = SerializerProvider();        serializerProvider.setNullValueSerializer(new CustomizeNullJsonSerializer                  .NullObjectJsonSerializer());
return objectMapper;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。