How to Configure ObjectMapper in Spring
Problem:
You want to configure ObjectMapper in Spring to serialize only the elements that are annotated with @JsonProperty. However, despite following the recommended instructions, the NumbersOfNewEvents class still contains all attributes when serialized.
Explanation:
In the custom CompanyObjectMapper, you've set the visibility checker to hide all fields and getters/setters by default. This prevents ObjectMapper from accessing and serializing the newAccepts and openRequests fields.
Solution:
To achieve the desired result, you can use a more targeted approach to configure the visibility checker. Here's an example:
public class CompanyObjectMapper extends ObjectMapper { public CompanyObjectMapper() { super(); SerializationConfig config = getSerializationConfig(); config.withView(Some.class) // Specify which view to use .withVisibility(JsonAutoDetect.Visibility.NONE) .withVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); } }
This configuration will allow the properties with the @JsonProperty annotation to be serialized, while keeping other fields hidden.
Spring Boot Configuration:
If you're using Spring Boot and Jackson 2.4.6 or higher, you can use the following configuration:
@Configuration public class JacksonConfiguration { @Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); // Enable default typing for polymorphic types mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); // Allow serialization of fields mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true); // Enable default view inclusion return mapper; } }
This configuration enables default typing for polymorphic types, allows the serialization of all fields, and enables default view inclusion.
The above is the detailed content of How to Configure Spring's ObjectMapper to Serialize Only @JsonProperty Annotated Elements?. For more information, please follow other related articles on the PHP Chinese website!