springboot return data to null

springboot use jackson parse the returned json data by default.

Processing method, returns the null field json - not displayed 

Profile adds spring.jackson.default-property-inclusion = non_null configuration

Processing method 2, in the null field returns json - Switch to the empty string

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
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;
 
import java.io.IOException;
 
/**
 * 处理 jackson 返回的null值
 * 返回json中的null值转为空字符串
 */
@Configuration
public class JacksonConfig {
 
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

 

Published 49 original articles · won praise 7 · views 10000 +

Guess you like

Origin blog.csdn.net/csdnzhang365/article/details/103445587