更新时间:2023-01-17 11:25:31
您需要使用 @JsonTypeInfo
注释注释您的类型,配置类型信息应该如何序列化。请参阅此页面以供参考。
You need to annotated your type with the @JsonTypeInfo
annotation and configure how the type information should be serialized. Refer this page for reference.
示例:
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));
}
}
输出:
{
"__class" : "***.JacksonClassInfo$Bean",
"field" : "value"
}
Bean{field='value'}