Customize how @JsonTypeInfo adds type information in serialized JSON

38 views Asked by At

I have an abstract class, e.g. lets take Animal and it have few child classes, Dog and Cat. I want when e.g if a Cat, Dog class object is serialized, its serialized as follows:

{
    "TYPE": "Cat",
    "DATA": {
        //some data
    }
}

{
    "TYPE": "Dog",
    "DATA": {
        //some data
    }
}

I have found a solution for this with Jackson using Field annotations, applying field annotations everywhere Animal abstract class is used and I am calling custom serializers/de-serializers. But when I am applying the same serializer at class level, during serialization it goes in an infinite loop trying to serialize same Animal object again and again.

here is the serializer:

public class JacksonSerializer extends JsonSerializer<Object> {
  private static final String CLASSNAME = "TYPE";
  private static final String DATA = "DATA";
  

  public JacksonSerializer() {
    // nothing
  }

  @Override
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) 
          throws IOException {
    jgen.writeStartObject();
    jgen.writeStringField(CLASSNAME, SerializationTypeMappingInfo.getTypeName(value));
    provider.defaultSerializeField(DATA, value, jgen);
    jgen.writeEndObject();
  }
}

I wanted to know if there is any way to achieve this using class level annotations, I want to avoid using field annotation every time I use this Animal class. Any way using @JsonTypeInfo or custom serializer/de-serializers using Jackson?

0

There are 0 answers