Jackson serializes json from null to empty object or empty string

You may encounter nulls in the project, and you don't want nulls when converting to JSON. You can add the following configuration to solve this problem.

One, add JacksonConfig configuration

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
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)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 关键代码-解决No serializer found for class java.lang.Object异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                //jsonGenerator.writeString("");//空串
                jsonGenerator.writeObject(new Object());//空对象
            }
        });
        return objectMapper;
    }

}

Two, attention

1 key code analysis

objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)

The role of the code is to solve the following exception

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: cloudpc.datasource.common.response.Result["data"])

2 @ConditionalOnMissingBean

It is an annotation to decorate the bean. The main realization is that after your bean is registered, if you register the same type of bean, it will not succeed. It will ensure that there is only one bean for you, that is, there is only one instance for you. When you register multiple identical beans, an exception will occur to tell the developer.

Generally speaking, for custom configuration classes, we should add @ConditionalOnMissingBean annotations to avoid the risk of multiple configurations being injected at the same time.

Three, reference

https://blog.csdn.net/sdyy321/article/details/40298081

https://www.cnblogs.com/long88-club/p/11361174.html

https://segmentfault.com/a/1190000008287502

http://www.cppcns.com/ruanjian/java/333889.html

Guess you like

Origin blog.csdn.net/cs373616511/article/details/111660503