Skip to content
Advertisement

Serialize objects to a map with the object class as the key?

I’m writing a application using Spring boot and jackson for JSON parsing. I need to handle another service which produces JSON like this:

{
  "task-id": 5081,
  "task-created-on": {
    "java.util.Date": 1631022026000
  }
}

Notably, certain fields like the date field here are serialized into a map with a single key-value pair, where the key is a java classname and the value is the actual value of the field.

I’ve been going through the jackson documentation and haven’t found anything about this format. Is there a way to configure jackson to produce and parse fields in this format?

At a minimum, I need to handle dates formatted this way. But I believe the service also uses this format for other objects, where the map key will be the name of some arbitrary java class and the value will be a map of its own. So I’d be interested in a solution that handles more than just dates if possible.

Advertisement

Answer

It is possible to solve the issue with the use of a custom JsonSerializer and applying the JsonSerialize over the fields in the pojo you are interested like below :

public class Task {

    @JsonProperty("task-id")
    private int taskId;

    @JsonProperty("task-created-on")
    @JsonSerialize(using = ObjectSerializer.class)
    Date taskCreatedOn; 
}

The custom serializer will use the JsonGenerator.html#writeObjectField to serialize a generic object (Date or other java class) as propertyname : {“classname” : value} :

public class ObjectSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object t, JsonGenerator jg, SerializerProvider sp) throws IOException {
        jg.writeStartObject();
        jg.writeObjectField(t.getClass().getName(), t);
        jg.writeEndObject();
    }

}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement