Jackson @JsonTypeInfo属性属性采用字符串值 [英] Jackson @JsonTypeInfo property attribute assumes string value
问题描述
说我有一些像这样的JSON
Say I have some JSON like so
[
{
'type' : {
'value': 'B'
}
},
{
'type' : {
'value': 'C'
}
}
]
是否可以使用jackson使用types值属性来告诉jackson对象是什么多态类型?例如,我尝试过类似的方法而没有任何运气
Is it possible to use jackson to use the types value property to tell jackson what polymorphic type the object is? For example, i've tried something along the lines of this without any luck
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.Property, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(name = "B", value = B.class),
@JsonSubTypes.Type(name = "C", value = C.class)
}
)
abstract class A {
private Type type;
}
@JsonTypeName(value = "B")
class B extends A {
}
@JsonTypeName(value = "C")
class C extends A {
}
class Type {
private String value;
}
推荐答案
Jackson似乎不支持使用嵌套在JSON中另一个对象中的String
来识别类型.您始终可以将自定义反序列化器用于此类操作.看起来像这样:
Using a String
nested in another object in JSON to discern the type doesn't seem to be supported by Jackson. You can always use a custom Deserializer for that sort of thing. It will look like this:
class ADeserializer extends JsonDeserializer<A> {
@Override public A deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
ObjectMapper mapper = (ObjectMapper) p.getCodec();
ObjectNode node = mapper.readTree(p);
String value = node.get("type").get("value").asText();
switch (value) {
case "B": return mapper.treeToValue(node, B.class);
case "C": return mapper.treeToValue(node, C.class);
default: return null;
}
}
}
并使用它注释抽象类以指定Deserializer:
and to use it annotate the abstract class to specify the Deserializer:
@JsonDeserialize(using = ADeserializer.class)
abstract class A {
以及具有空@JsonDeserialize
的派生类,以避免再次调用相同的自定义反序列化器(StackOverflowError
).
and derived classes with empty @JsonDeserialize
to avoid calling the same custom Deserializer again (StackOverflowError
).
@JsonDeserialize
class B extends A {
上面不需要@JsonTypeName
,@JsonTypeInfo
和@JsonSubTypes
.
我查看了其他一些选项,例如自定义扩展了
I had a look at a few other options like a custom JsonTypeIdResolver and this answer that extends AsPropertyTypeDeserializer but couldn't get either of these to work in your case.
这篇关于Jackson @JsonTypeInfo属性属性采用字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!