[英]Deserialize JSON using Jackson with different types of object
I am trying to deserialize this payload:我正在尝试反序列化此有效负载:
{
"commonField": {"a": "1234"},
"X": {"c": "1234", "d": "5678"}
}
but "X" could be "Y" with a different definition.但“X”可能是具有不同定义的“Y”。
My idea is having a DTO with the commonField and an Interface to be implemented by "X" or "Y".我的想法是有一个带有 commonField 的 DTO 和一个由“X”或“Y”实现的接口。
I have been trying with JsonSubTypes but didn't work ( snippet ) Any idea?我一直在尝试使用 JsonSubTypes 但没有用(片段)知道吗?
try this:尝试这个:
JSON.parse(JSON.stringify({
"commonField": {"a": "1234"},
"X": {"c": "1234", "d": "5678"}
}))
I'd probably deserialize to:我可能会反序列化为:
public class Payload {
public CommonType commonField;
public X x;
public Y y;
}
Fields not present in the JSON will remain null
. JSON 中不存在的字段将保留
null
。
Edit编辑
a single field with polymorphic content
具有多态内容的单个字段
You can achieve this with a few setters:您可以通过一些设置器来实现这一点:
public class Payload {
public CommonType commonField;
private TheInterface polyField;
public TheInterface getPolyField() {
return polyField;
}
public void setX(X x) {
polyfield = x;
}
public void setY(Y y) {
polyfield = y;
}
}
assuming that X
and Y
are declared to implement TheInterface
.假设
X
和Y
被声明为实现TheInterface
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.