November 11, 2012

“Custom Serialization of Models with Jackson”

Today, I learned that you can customize the code that is executed to serialize an object for Jackson. I’m currently implementing a service using Dropwizard with Hibernate Spatial and serializing the Point object as JSON led to infinite recursion issues. As a fix, I wrote a serializer for the Point class for Jackson:

Custom Jackson serializer

public class CustomPointSerializer extends JsonSerializer<Point> {
   public void serialize(Point value, JsonGenerator jgen, SerializerProvider provider)
           throws IOException, JsonGenerationException {
       String result = "{'x': " + value.getX() + ", 'y': " + value.getY() + "}";