问题描述
如果我有这样的类结构:
If I have a class structure like so:
public abstract class Parent {
private Long id;
...
}
public class SubClassA extends Parent {
private String stringA;
private Integer intA;
...
}
public class SubClassB extends Parent {
private String stringB;
private Integer intB;
...
}
是否有其他方法可以反序列化不同的 @JsonTypeInfo
?在我的父类上使用此注释:
Is there an alternative way to deserialize different then @JsonTypeInfo
? Using this annotation on my parent class:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "objectType")
我宁愿不必强迫我的API客户包含objectType :SubClassA
反序列化 Parent
子类。
I would rather not have to force clients of my API to include "objectType": "SubClassA"
to deserialize a Parent
subclass.
而不是使用 @JsonTypeInfo
,杰克逊是否提供了一种注释子类的方法,并通过一个独特的属性将其与其他子类区分开来?在上面的示例中,这将是如果JSON对象具有stringA:...
将其反序列化为 SubClassA
,如果它有stringB:...
将其反序列化为 SubClassB
。
Instead of using @JsonTypeInfo
, does Jackson provide a way to annotate a subclass and distinguish it from other subclasses via a unique property? In my example above, this would be something like, "If a JSON object has "stringA": ...
deserialize it as SubClassA
, if it has "stringB": ...
deserialize it as SubClassB
".
推荐答案
这就像 @JsonTypeInfo
和 @JsonSubTypes
应该用于但是我已经选择了文档,并且没有任何可以提供的属性看起来与你所描述的相匹配。
This feels like something @JsonTypeInfo
and @JsonSubTypes
should be used for but I've picked through the docs and none of the properties that can be supplied quite seem to match what you're describing.
您可以编写一个自定义反序列化器,它以非标准方式使用 @JsonSubTypes
'name和value属性来完成您想要的任务。将在您的基类上提供反序列化器和 @JsonSubTypes
,并且反序列化器将使用name值来检查是否存在属性,如果存在,则反序列化将JSON放入value属性中提供的类中。你的类看起来像这样:
You could write a custom deserializer that uses @JsonSubTypes
' "name" and "value" properties in a non-standard way to accomplish what you want. The deserializer and @JsonSubTypes
would be supplied on your base class and the deserializer would use the "name" values to check for the presence of a property and if it exists, then deserialize the JSON into the class supplied in the "value" property. Your classes would then look something like this:
@JsonDeserialize(using = PropertyPresentDeserializer.class)
@JsonSubTypes({
@Type(name = "stringA", value = SubClassA.class),
@Type(name = "stringB", value = SubClassB.class)
})
public abstract class Parent {
private Long id;
...
}
public class SubClassA extends Parent {
private String stringA;
private Integer intA;
...
}
public class SubClassB extends Parent {
private String stringB;
private Integer intB;
...
}
这篇关于用Jackson反序列化多态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!