I am trying to deserialize this payload:
{
"commonField": {"a": "1234"},
"X": {"c": "1234", "d": "5678"}
}
but "X" could be "Y" with a different definition.
My idea is having a DTO with the commonField and an Interface to be implemented by "X" or "Y".
I have been trying with JsonSubTypes but didn't work ( snippet ) Any idea?
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
.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.