springboot 项目,返回的实体类里面字段是null ,现在想要为空应该是““,空字符串,而不是null

目录

  • 1 问题
  • 2 实现

1 问题

返回给前端的数据,如果数据库的字段没有数据,给返回的是null

springboot 项目,返回的实体类里面字段是null ,现在想要为空应该是““,空字符串,而不是null_第1张图片

要变成这个,全局都变成这样

springboot 项目,返回的实体类里面字段是null ,现在想要为空应该是““,空字符串,而不是null_第2张图片

2 实现

springboot返回给页面的json数据中,如果有数据为null,则返回空字符串。

springboot默认使用jackson解析返回json数据。



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值
 *
 */
@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;
    }
}

只需要加上以上的配置就可以了

你可能感兴趣的:(工作工具类,spring,boot,后端,java)