How do I use a custom Serializer with Jackson?

JavaJsonSerializationJackson

Java Problem Overview


I have two Java classes that I want to serialize to JSON using Jackson:

public class User {
    public final int id;
    public final String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

public class Item {
    public final int id;
    public final String itemNr;
    public final User createdBy;

    public Item(int id, String itemNr, User createdBy) {
        this.id = id;
        this.itemNr = itemNr;
        this.createdBy = createdBy;
    }
}

I want to serialize an Item to this JSON:

{"id":7, "itemNr":"TEST", "createdBy":3}

with User serialized to only include the id. I will also be able to serilize all user objects to JSON like:

{"id":3, "name": "Jonas", "email": "[email protected]"}

So I guess that I need to write a custom serializer for Item and tried with this:

public class ItemSerializer extends JsonSerializer<Item> {

@Override
public void serialize(Item value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,
		JsonProcessingException {
	jgen.writeStartObject();
	jgen.writeNumberField("id", value.id);
	jgen.writeNumberField("itemNr", value.itemNr);
	jgen.writeNumberField("createdBy", value.user.id);
	jgen.writeEndObject();
}

}

I serialize the JSON with this code from Jackson How-to: Custom Serializers:

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                              new Version(1,0,0,null));
simpleModule.addSerializer(new ItemSerializer());
mapper.registerModule(simpleModule);
StringWriter writer = new StringWriter();
try {
	mapper.writeValue(writer, myItem);
} catch (JsonGenerationException e) {
	e.printStackTrace();
} catch (JsonMappingException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

But I get this error:

Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() (use alternative registration method?)
	at org.codehaus.jackson.map.module.SimpleSerializers.addSerializer(SimpleSerializers.java:62)
	at org.codehaus.jackson.map.module.SimpleModule.addSerializer(SimpleModule.java:54)
	at com.example.JsonTest.main(JsonTest.java:54)

How can I use a custom Serializer with Jackson?


This is how I would do it with Gson:

public class UserAdapter implements JsonSerializer<User> {
	
	@Override 
	public JsonElement serialize(User src, java.lang.reflect.Type typeOfSrc,
			JsonSerializationContext context) {
		return new JsonPrimitive(src.id);
	}
}

	GsonBuilder builder = new GsonBuilder();
	builder.registerTypeAdapter(User.class, new UserAdapter());
	Gson gson = builder.create();
	String json = gson.toJson(myItem);
	System.out.println("JSON: "+json);

But I need to do it with Jackson now, since Gson doesn't have support for interfaces.

Java Solutions


Solution 1 - Java

You can put @JsonSerialize(using = CustomDateSerializer.class) over any date field of object to be serialized.

public class CustomDateSerializer extends SerializerBase<Date> {

    public CustomDateSerializer() {
	    super(Date.class, true);
    }

    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
		throws IOException, JsonProcessingException {
	    SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'ZZZ (z)");
	    String format = formatter.format(value);
	    jgen.writeString(format);
    }

}

Solution 2 - Java

As mentioned, @JsonValue is a good way. But if you don't mind a custom serializer, there's no need to write one for Item but rather one for User -- if so, it'd be as simple as:

public void serialize(Item value, JsonGenerator jgen,
    SerializerProvider provider) throws IOException,
    JsonProcessingException {
  jgen.writeNumber(id);
}

Yet another possibility is to implement JsonSerializable, in which case no registration is needed.

As to error; that is weird -- you probably want to upgrade to a later version. But it is also safer to extend org.codehaus.jackson.map.ser.SerializerBase as it will have standard implementations of non-essential methods (i.e. everything but actual serialization call).

Solution 3 - Java

I tried doing this too, and there is a mistake in the example code on the Jackson web page that fails to include the type (.class) in the call to addSerializer() method, which should read like this:

simpleModule.addSerializer(Item.class, new ItemSerializer());

In other words, these are the lines that instantiate the simpleModule and add the serializer (with the prior incorrect line commented out):

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                          new Version(1,0,0,null));
// simpleModule.addSerializer(new ItemSerializer());
simpleModule.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(simpleModule);

FYI: Here is the reference for the correct example code: http://wiki.fasterxml.com/JacksonFeatureModules

Solution 4 - Java

Use @JsonValue:

public class User {
    int id;
    String name;

    @JsonValue
    public int getId() {
        return id;
    }
}

@JsonValue only works on methods so you must add the getId method. You should be able to skip your custom serializer altogether.

Solution 5 - Java

I wrote an example for a custom Timestamp.class serialization/deserialization, but you could use it for what ever you want.

When creating the object mapper do something like this:

public class JsonUtils {

	public static ObjectMapper objectMapper = null;

	static {
		objectMapper = new ObjectMapper();
		SimpleModule s = new SimpleModule();
		s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
		s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
		objectMapper.registerModule(s);
	};
}

for example in java ee you could initialize it with this:

import java.time.LocalDateTime;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

@Provider
public class JacksonConfig implements ContextResolver<ObjectMapper> {

	private final ObjectMapper objectMapper;

	public JacksonConfig() {
		objectMapper = new ObjectMapper();
		SimpleModule s = new SimpleModule();
		s.addSerializer(Timestamp.class, new TimestampSerializerTypeHandler());
		s.addDeserializer(Timestamp.class, new TimestampDeserializerTypeHandler());
		objectMapper.registerModule(s);
	};

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

where the serializer should be something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampSerializerTypeHandler extends JsonSerializer<Timestamp> {

    @Override
    public void serialize(Timestamp value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        String stringValue = value.toString();
        if(stringValue != null && !stringValue.isEmpty() && !stringValue.equals("null")) {
        	jgen.writeString(stringValue);
        } else {
        	jgen.writeNull();
        }
    }

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}

and deserializer something like this:

import java.io.IOException;
import java.sql.Timestamp;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class TimestampDeserializerTypeHandler extends JsonDeserializer<Timestamp> {
    
    @Override
	public Timestamp deserialize(JsonParser jp, DeserializationContext ds) throws IOException, JsonProcessingException {
    	SqlTimestampConverter s = new SqlTimestampConverter();
    	String value = jp.getValueAsString();
    	if(value != null && !value.isEmpty() && !value.equals("null"))
    		return (Timestamp) s.convert(Timestamp.class, value);
    	return null;
	}

    @Override
    public Class<Timestamp> handledType() {
        return Timestamp.class;
    }
}

Solution 6 - Java

These are behavior patterns I have noticed while trying to understand Jackson serialization.

  1. Assume there is an object Classroom and a class Student. I've made everything public and final for ease.

    public class Classroom { public final double double1 = 1234.5678; public final Double Double1 = 91011.1213; public final Student student1 = new Student(); }

    public class Student { public final double double2 = 1920.2122; public final Double Double2 = 2324.2526; }

  2. Assume that these are the serializers we use for serializing the objects into JSON. The writeObjectField uses the object's own serializer if it is registered with the object mapper; if not, then it serializes it as a POJO. The writeNumberField exclusively only accepts primitives as arguments.

    public class ClassroomSerializer extends StdSerializer { public ClassroomSerializer(Class t) { super(t); }

     @Override
     public void serialize(Classroom value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
         jgen.writeStartObject();
         jgen.writeObjectField("double1-Object", value.double1);
         jgen.writeNumberField("double1-Number", value.double1);
         jgen.writeObjectField("Double1-Object", value.Double1);
         jgen.writeNumberField("Double1-Number", value.Double1);
         jgen.writeObjectField("student1", value.student1);
         jgen.writeEndObject();
     }
    

    }

    public class StudentSerializer extends StdSerializer { public StudentSerializer(Class t) { super(t); }

     @Override
     public void serialize(Student value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
         jgen.writeStartObject();
         jgen.writeObjectField("double2-Object", value.double2);
         jgen.writeNumberField("double2-Number", value.double2);
         jgen.writeObjectField("Double2-Object", value.Double2);
         jgen.writeNumberField("Double2-Number", value.Double2);
         jgen.writeEndObject();
     }
    

    }

  3. Register only a DoubleSerializer with DecimalFormat output pattern ###,##0.000, in SimpleModule and the output is:

    { "double1" : 1234.5678, "Double1" : { "value" : "91,011.121" }, "student1" : { "double2" : 1920.2122, "Double2" : { "value" : "2,324.253" } } }

You can see that the POJO serialization differentiates between double and Double, using the DoubleSerialzer for Doubles and using a regular String format for doubles.

  1. Register DoubleSerializer and ClassroomSerializer, without the StudentSerializer. We expect that the output is such that if we write a double as an object, it behaves like a Double, and if we write a Double as a number, it behaves like a double. The Student instance variable should be written as a POJO and follow the pattern above since it does not register.

    { "double1-Object" : { "value" : "1,234.568" }, "double1-Number" : 1234.5678, "Double1-Object" : { "value" : "91,011.121" }, "Double1-Number" : 91011.1213, "student1" : { "double2" : 1920.2122, "Double2" : { "value" : "2,324.253" } } }

  2. Register all serializers. The output is:

    { "double1-Object" : { "value" : "1,234.568" }, "double1-Number" : 1234.5678, "Double1-Object" : { "value" : "91,011.121" }, "Double1-Number" : 91011.1213, "student1" : { "double2-Object" : { "value" : "1,920.212" }, "double2-Number" : 1920.2122, "Double2-Object" : { "value" : "2,324.253" }, "Double2-Number" : 2324.2526 } } exactly as expected.

Another important note: If you have multiple serializers for the same class registered with the same Module, then the Module will select the serializer for that class that is most recently added to the list. This should not be used - it's confusing and I am not sure how consistent this is

Moral: if you want to customize serialization of primitives in your object, you must write your own serializer for the object. You cannot rely on the POJO Jackson serialization.

Solution 7 - Java

Jackson's JSON Views might be a simpler way of achieving your requirements, especially if you have some flexibility in your JSON format.

If {"id":7, "itemNr":"TEST", "createdBy":{id:3}} is an acceptable representation then this will be very easy to achieve with very little code.

You would just annotate the name field of User as being part of a view, and specify a different view in your serialisation request (the un-annotated fields would be included by default)

For example: Define the views:

public class Views {
    public static class BasicView{}
	public static class CompleteUserView{}
}

Annotate the User:

public class User {
    public final int id;
    
    @JsonView(Views.CompleteUserView.class)
    public final String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

And serialise requesting a view which doesn't contain the field you want to hide (non-annotated fields are serialised by default):

objectMapper.getSerializationConfig().withView(Views.BasicView.class);

Solution 8 - Java

In my case (Spring 3.2.4 and Jackson 2.3.1), XML configuration for custom serializer:

<mvc:annotation-driven>
	<mvc:message-converters register-defaults="false">
		<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
			<property name="objectMapper">
				<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
					<property name="serializers">
						<array>
							<bean class="com.example.business.serializer.json.CustomObjectSerializer"/>
						</array>
					</property>
				</bean>
			</property>
		</bean>
	</mvc:message-converters>
</mvc:annotation-driven>

was in unexplained way overwritten back to default by something.

This worked for me:

CustomObject.java

@JsonSerialize(using = CustomObjectSerializer.class)
public class CustomObject {

	private Long value;

	public Long getValue() {
		return value;
	}

	public void setValue(Long value) {
		this.value = value;
	}
}

CustomObjectSerializer.java

public class CustomObjectSerializer extends JsonSerializer<CustomObject> {

	@Override
	public void serialize(CustomObject value, JsonGenerator jgen,
		SerializerProvider provider) throws IOException,JsonProcessingException {
		jgen.writeStartObject();
		jgen.writeNumberField("y", value.getValue());
		jgen.writeEndObject();
	}

	@Override
	public Class<CustomObject> handledType() {
		return CustomObject.class;
	}
}

No XML configuration (<mvc:message-converters>(...)</mvc:message-converters>) is needed in my solution.

Solution 9 - Java

The problem in your case is the ItemSerializer is missing the method handledType() which needs to be overridden from JsonSerializer

public class ItemSerializer extends JsonSerializer<Item> {
    
    @Override
    public void serialize(Item value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeNumberField("itemNr", value.itemNr);
        jgen.writeNumberField("createdBy", value.user.id);
        jgen.writeEndObject();
    }

   @Override
   public Class<Item> handledType()
   {
    return Item.class;
   }
}

Hence you are getting the explicit error that handledType() is not defined

Exception in thread "main" java.lang.IllegalArgumentException: JsonSerializer of type com.example.ItemSerializer does not define valid handledType() 

Hope it helps someone. Thanks for reading my answer.

Solution 10 - Java

If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.

[ see also: https://stackoverflow.com/questions/910374/why-does-java-have-transient-variables/910522#910522 ]

Solution 11 - Java

You have to override method handledType and everything will work

@Override
public Class<Item> handledType()
{
  return Item.class;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonasView Question on Stackoverflow
Solution 1 - JavaMoesioView Answer on Stackoverflow
Solution 2 - JavaStaxManView Answer on Stackoverflow
Solution 3 - JavapmhargisView Answer on Stackoverflow
Solution 4 - Javahenrik_lundgrenView Answer on Stackoverflow
Solution 5 - JavamadxView Answer on Stackoverflow
Solution 6 - Javalaughing_manView Answer on Stackoverflow
Solution 7 - JavaPaul MView Answer on Stackoverflow
Solution 8 - Javauser11153View Answer on Stackoverflow
Solution 9 - JavaSanjay BharwaniView Answer on Stackoverflow
Solution 10 - JavaMike GView Answer on Stackoverflow
Solution 11 - JavaSergey KukurudzyakView Answer on Stackoverflow