Rest对象转换为json时,value值为null,key是否需要返回逻辑

1、注册自定义转换配置:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

@Configuration
public class WebConfiguration  {

    @Bean
    public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper mapper = converter.getObjectMapper();
        // 为mapper注册一个带有SerializerModifier的Factory,此modifier主要做的事情为:设置空值处理序列化对象,针对空值做处理,防止值为空,key也显示为空
        mapper.setSerializerFactory(mapper.getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
        converter.setSupportedMediaTypes(ImmutableList.of(MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON));
        return converter;
    }
}

2、定义序列化逻辑对象:

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.List;

public class MyBeanSerializerModifier extends BeanSerializerModifier {

    private JsonSerializer _nullArrayJsonSerializer = new MyNullJsonSerializer();  //NullSerializer.instance; 直接用这个也可以,用这个不需要新建对象

    @Override
    public List changeProperties(SerializationConfig config, BeanDescription beanDesc,
                                                     List beanProperties) {
        // 循环所有的beanPropertyWriter
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = beanProperties.get(i);
            // 给writer注册一个自己的nullSerializer
            writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
        }
        return beanProperties;
    }
    protected JsonSerializer defaultNullArrayJsonSerializer() {
        return _nullArrayJsonSerializer;
    }
} 
  

3、自定义空值情况赋值方法

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;

public class MyNullJsonSerializer extends JsonSerializer {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeNull();
    }
} 
  

4、源码逻辑如下,其实是当值value为空时,会判断有没有空值处理对象_nullSerializer,有的话就会做key值赋值,并调用对象针对value做处理。相当于1、2、3的步骤是通过适配源码,修改源码的_nullSerializer对象,达到目的

Rest对象转换为json时,value值为null,key是否需要返回逻辑_第1张图片

你可能感兴趣的:(架构设计,java,json,java,spring,boot)