When the Java object is empty, the object properties are not displayed, or null is converted to ""

the first method: 

@JsonInclude(JsonInclude.Include.NON_NULL)

Add this annotation to the object name corresponding to the entity class, or the class name.

Include.ALWAYS attributes are serialized.
Include.NON_DEFAULT attribute is the default value. Not serialized. 
Include.NON_EMPTY attribute is empty ("") or NULL. 
Include.NON_NULL attribute is NULL. Not serialized 

Such as:

private Integer id;
 
@JsonInclude(JsonInclude.Include.NON_NULL)
private String resourceName;

At this time, if resourceName is null, the attribute will not be displayed.

The disadvantage of this method is that if it is empty, the entire property is gone. Here is a way to talk about turning null to "".

The second method: customize an objectmapper

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

Note that this method will convert the object to an empty string when the list, map, and enumeration are null. This is a drawback. Use it according to your needs.

The third method: directly set the attribute default value

Is to set the property default value when initializing the entity class

Such as:

private String name="";

 

Guess you like

Origin blog.csdn.net/qq_36802726/article/details/88895444