设置一个配置文件,用以注入自己的json工厂
@Configuration
public class JsonConfig {
@Bean
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = converter.getObjectMapper();
// 为mapper注册一个带有SerializerModifier的Factory,此modifier主要做的事情为:当序列化类型为array,list、set时,当值为空时,序列化成[]
mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
return converter;
}
}
再对需要处理的情况进行处理
public class MyBeanSerializerModifier extends BeanSerializerModifier {
private JsonSerializer<Object> _nullArrayJsonSerializer = new MyNullArrayJsonSerializer();
private JsonSerializer<Object> _nullObjectJsonSerializer = new MyNullObjectJsonSerializer();
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
List<BeanPropertyWriter> beanProperties) {
// 循环所有的beanPropertyWriter
for (int i = 0; i < beanProperties.size(); i++) {
BeanPropertyWriter writer = beanProperties.get(i);
// 判断字段的类型,如果是array,list,set则注册nullSerializer
if (isArrayType(writer)) {
//给writer注册一个自己的nullSerializer
writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
}else if(isObjectType(writer)){
writer.assignNullSerializer(this.defaultNullObjectJsonSerializer());
}
}
return beanProperties;
}
private boolean isObjectType(BeanPropertyWriter writer) {
Class<?> clazz = writer.getPropertyType();
return !clazz.isPrimitive() && !clazz.equals(String.class)
&& clazz.isAssignableFrom(Object.class);
}
// 判断是什么类型
protected boolean isArrayType(BeanPropertyWriter writer) {
Class<?> clazz = writer.getPropertyType();
return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
}
protected JsonSerializer<Object> defaultNullArrayJsonSerializer() {
return _nullArrayJsonSerializer;
}
protected JsonSerializer<Object> defaultNullObjectJsonSerializer() {
return _nullObjectJsonSerializer;
}
}
网友评论