Wednesday, September 21, 2011

Jersey + Jackson: Serialize only annotated fields or methods with @JsonProperty

By default, when serializing objects, Jackson will auto-detect all public no-argument non-static getter methods and include them as properties in the final result (JSON string). I wanted Jackson to use only annotated methods and ignore rest of the methods of my object. To accomplish this we need to turn off the AUTO_DETECT_GETTERS feature in SerializationConfig object by configuring our ObjectMapper which holds an instance of SerializationConfig. I couldn't manage to inject a preconfigured SerializationConfig or ObjectMapper object. Then I found out that we need create an ObjectMapper provider class that implements ContextResolver, and annotate it with @Provider. This provider should then return an instance of ObjectMapper. This is where we will configure the object.



So, here's the provider class:
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

	private ObjectMapper objectMapper;

	public ObjectMapperProvider() {
		objectMapper = new ObjectMapper();
		objectMapper.configure(SerializationConfig.Feature.AUTO_DETECT_GETTERS, false);
		objectMapper.configure(SerializationConfig.Feature.AUTO_DETECT_IS_GETTERS, false);
	}

	@Override
	public ObjectMapper getContext(Class type) {
		return objectMapper;
	}

}
Note: I've also disabled the AUTO_DETECT_IS_GETTERS feature to prevent boolean is* methods from being auto-detected.
The provider class must be made known to Jackson. One way is to place it in one of Jackson's search packages, that is, in one the (sub)packages specified in the com.sun.jersey.config.property.packages parameter. See this post for more details.

No comments:

Post a Comment