dug
dug

Reputation: 2335

Changing the default serialization behavior in Jackson

I am using the Jackson library to write custom serializers, and register them inside of a custom ObjectMapper. However, I also want to change the default serialization to simply output the string representation of the object when a more specific custom serialization has not been written.

For example, say I have written custom serializers for classes "Map" and "Entry", in addition to the default serializer. Then the serialization module within my custom ObjectMapper might look like this:

SimpleModule module = new SimpleModule("module", new Version(0, 1, 0, "alpha", null, null));
module.addSerializer(Entry.class, new EntryJsonSerializer());
module.addSerializer(Map.class, new MapJsonSerializer());
module.addSerializer(Object.class, new DefaultJsonSerializer());
this.registerModule(module);

However, I'm finding that the module will use DefaultJsonSerializer to serialize Map and Entry objects (as they are also Object objects).

How can I change the default serialization behavior, while ensuring Entry and Map objects are serialized as intended?

Upvotes: 2

Views: 3073

Answers (2)

dug
dug

Reputation: 2335

I've gotten around the problem by writing a single serializer and using a series of if statements to implement prioritization:

public final class UnifiedJsonSerializer extends JsonSerializer<Object> {
    @Override
    public void serialize(Object object, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        if (object instanceof Entry) {
            // Entry serialization code
        } else if (object instanceof Map) {
            // Map serialization code
        } else  {
            // default serialization code
        }
}

Upvotes: 1

StaxMan
StaxMan

Reputation: 116512

The problem is probably that the actual type of values (say, String) is used for locating serializers.

One solution would be to register serializers for value types, if you know them.

Alternatively, you could force use of static typing; this would make serializer lookup use declared (static) type, not actual runtime type. This can be done with:

objectMapper.enable(MapperFeature.USE_STATIC_TYPING);

Upvotes: 1

Related Questions