Remove null and empty fields from JSON return value under spring boot



In the development process, we need to return the front-end json format data uniformly, but the return value of some interfaces has meaningless fields such as null or "".

It not only affects understanding, but also wastes bandwidth. At this time, we can do it uniformly, not return empty fields, or convert NULL to "". Spring's built-in json processing framework is Jackson. We can configure it to achieve the purpose

Just look at the code, it's very simple.


/**
 * <Return json null value to remove null and ""> <Function detailed description>
 *
 * @author gogym
 * @version October 13, 2017
 * @see JacksonConfig
 * @since
 */
@Configuration
public class JacksonConfig
{
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder)
    {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        // Set the mapper object through this method, and all serialized objects will be serialized according to the modified rules
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT property is the default value not serialized
        // If the Include.NON_EMPTY property is empty ("") or NULL is not serialized, the returned json does not have this field. This will save more traffic on mobile
        // Include.NON_NULL attribute is NULL and not serialized, that is, the field that is null does not participate in serialization
        //objectMapper.setSerializationInclusion(Include.NON_EMPTY);

        // Field is reserved, convert null value to ""
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
    {
        @Override
        public void serialize(Object o, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider)
                throws IOException, JsonProcessingException
        {
            jsonGenerator.writeString("");
        }
    });
        return objectMapper;
    }
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325392948&siteId=291194637