junhanlin junhanlin - 3 months ago 41
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:

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder()
{
return new Jackson2ObjectMapperBuilder()
{

@Override
public void configure(ObjectMapper objectMapper)
{
super.configure(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
@JsonAutoDetect
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

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.

https://github.com/FasterXML/jackson-docs/wiki/JacksonMixInAnnotations

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

https://github.com/Antibrumm/jackson-antpathfilter