Serializing JSON with class metadata



I’ve used both Gson and Jackson and both of them offer a way to deal with polymorphism. For example, with Jackson you need to declare the class with a @JsonSubTypes and add each and every @JsonSubTypes.Type you have. Similar thing happens with Gson.

My question is if there is an option to make it work like with how MongoDB serializes data. It automatically adds a _class metadata field. With this method, you don’t need to manually register every subtype you’ve created.

Is it possible?

Answer

You can achieve this with jackson:

@JsonTypeInfo(use = Id.CLASS, include = As.PROPERTY, property = "_class")
public abstract class AbstractModel {
    
}

public class ModelA extends AbstractModel {
    
}
...
mapper.writeValue(System.out, new ModelA());

Outputs:

{
  "_class" : "demo.ModelA"
}

This way you dont have to add json subtypes for all types you add.



Source: stackoverflow