假设您的 JSON 文档如下:
{
"type": "foo",
"data": {
"someCommonProperty": "common property",
"fooProperty": "foo specific property"
}
}
{
"type": "bar",
"data": {
"someCommonProperty": "common property",
"barProperty": "bar specific property"
}
}
您可以使用:
public class Wrapper {
private String type;
@JsonTypeInfo(use = Id.NAME, property = "type", include = As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = Foo.class, name = "foo"),
@JsonSubTypes.Type(value = Bar.class, name = "bar")
})
private AbstractData data;
// Getters and setters
}
public abstract class AbstractData {
private String someCommonProperty;
// Getters and setters
}
public class Foo extends AbstractData {
private String fooProperty;
// Getters and setters
}
public class Bar extends AbstractData {
private String barProperty;
// Getters and setters
}
在这种方法中,@JsonTypeInfo https://fasterxml.github.io/jackson-annotations/javadoc/2.9/com/fasterxml/jackson/annotation/JsonTypeInfo.html设置为使用type
as an 外部财产 https://fasterxml.github.io/jackson-annotations/javadoc/2.9/com/fasterxml/jackson/annotation/JsonTypeInfo.As.html#EXTERNAL_PROPERTY确定映射的正确类别data
财产。 JSON 文档可以反序列化如下:
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(json, Wrapper.class);