You need to annotated your type with the @JsonTypeInfo
annotation and configure how the type information should be serialized. Refer this page for reference.
Example:
public class JacksonClassInfo {
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "__class")
public static class Bean {
public final String field;
@JsonCreator
public Bean(@JsonProperty("field") String field) {
this.field = field;
}
@Override
public String toString() {
return "Bean{" +
"field='" + field + ''' +
'}';
}
}
public static void main(String[] args) throws IOException {
Bean bean = new Bean("value");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bean);
System.out.println(json);
System.out.println(mapper.readValue(json, Bean.class));
}
}
Output:
{
"__class" : "stackoverflow.JacksonClassInfo$Bean",
"field" : "value"
}
Bean{field='value'}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…