junhanlin junhanlin - 1 year ago 233
JSON Question

Spring+Jackson: How to set visibility of a class without using @JsonAutoDetect annotation

In my spring-boot application, I have a global configuration on Jackson's ObjectMapper which told Jackson not to serialize object by fields but getters:

public Jackson2ObjectMapperBuilder objectMapperBuilder()
return new Jackson2ObjectMapperBuilder()

public void configure(ObjectMapper objectMapper)
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY);
objectMapper.setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY);



However, now I'm dealing with a special case. I need to serialize a class which is not written by myself (a class form dependnecy library). Since the class does not declared getters, Jackson will ignore those fields.
Here's how the external class look like:

public class DirectionsResult
public GeocodedWaypoint geocodedWaypoints[];
public DirectionsRoute routes[];

Although using
annotation can customerize a class's visibility for Jackson, this does not work with external classes.
So how can I set visibility of a class without using @JsonAutoDetect annotation and also not to change the global configuration?

Answer Source

You should be able to use jacksons MixIn feature. With this approach you can control all the configuration of a class by another class definition of your choice.


You can also check out one of my github projects to see the use of that feature:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download