美文网首页
springboot DTO返回数据为null时返回空字符串

springboot DTO返回数据为null时返回空字符串

作者: 小芃同学 | 来源:发表于2019-11-19 10:46 被阅读0次

    一、不返回null值

    在yml配置文件中添加如下配置即可
    jackson:
    default-property-inclusion: non_null

    二、遇到null值时返回空字符串,代码如下

    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 com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
    import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
    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;
    
    @Configuration
    public class JacksonConfiguration {
    
        /**
         * Support for Hibernate types in Jackson.
         */
        @Bean
        public Hibernate5Module hibernate5Module() {
            return new Hibernate5Module();
        }
    
        /**
         * Jackson Afterburner module to speed up serialization/deserialization.
         */
        @Bean
        public AfterburnerModule afterburnerModule() {
            return new AfterburnerModule();
        }
    
        @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;
        }
    }
    

    相关文章

      网友评论

          本文标题:springboot DTO返回数据为null时返回空字符串

          本文链接:https://www.haomeiwen.com/subject/cskwictx.html