杰克逊根据类型反序列化 [英] Jackson deserialize based on type
问题描述
让我们说我使用以下格式的JSON:
Lets say I have JSON of the following format:
{
"type" : "Foo"
"data" : {
"object" : {
"id" : "1"
"fizz" : "bizz"
...
},
"metadata" : {
...
},
"owner" : {
"name" : "John"
...
}
}
}
我试图避免自定义反序列化器,并尝试将上述JSON(称为Wrapper.java)反序列化为Java POJO. 类型"字段指示对象"反序列化,即. type = foo表示使用Foo.java反序列化"object"字段. (如果type = Bar,则使用Bar.java反序列化对象字段).元数据/所有者将始终使用相同的反序列化方式,每个方法都使用一个简单的带有Jackson注释的Java类.有没有一种方法可以使用注解来做到这一点?如果没有,该如何使用自定义解串器完成?
I am trying to avoid custom deserializer and attempting to deserialize the above JSON (called Wrapper.java) into Java POJOs. The "type" field dictates the "object" deserialization ie. type = foo means the deserialize the "object" field using the Foo.java. (if type = Bar, use Bar.java to deserialize the object field). Metadata/owner will always deserialize the same way using a simple Jackson annotated Java class for each. Is there a way to accomplish this using annotations? If not, how can this be done using a custom deserializer?
推荐答案
仅注释方法
或者替代自定义反序列化器方法,对于仅注释的解决方案,您可以采用以下方法(类似于一种方法)描述在 Spunc的答案中,但使用type
作为
Annotations-only approach
Alternatively to the custom deserializer approach, you can have the following for an annotations-only solution (similar to the one described in Spunc's answer, but using type
as an external property):
public abstract class AbstractData {
private Owner owner;
private Metadata metadata;
// Getters and setters
}
public static final class FooData extends AbstractData {
private Foo object;
// Getters and setters
}
public static final class BarData extends AbstractData {
private Bar object;
// Getters and setters
}
public class Wrapper {
private String type;
@JsonTypeInfo(use = Id.NAME, property = "type", include = As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = FooData.class, name = "Foo"),
@JsonSubTypes.Type(value = BarData.class, name = "Bar")
})
private AbstractData data;
// Getters and setters
}
In this approach, @JsonTypeInfo
is set to use type
as an external property to determine the right class to map the data
property.
JSON文档可以反序列化如下:
The JSON document can be deserialized as following:
ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(json, Wrapper.class);
这篇关于杰克逊根据类型反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!