学无先后,达者为师

网站首页 编程语言 正文

jackson中对null的处理

作者:LoveTrainHY 更新时间: 2022-04-11 编程语言

当我们在项目中遇到null值,在转换json的时候却不想让他显示为null,而是需要显示一个空字符串,这时需要创建一个配置类。
代码如下:

package com.demo.jsonconfig

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;

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
//jacksonObjectMapper类提供一些功能将转换成Java对象匹配JSON结构
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
 //重写类中的serialize,指定出现null值是返回""字符串
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

                
    
        

原文链接:https://blog.csdn.net/LoveTrainHY/article/details/121990330