I'd like to map a JSON to POJO. The JSON format is:
{
user: "123abc",
messages: [
{"type":"A", "args": {"a":"str", "b":0} },
{"type":"B", "args": {"c":true, "d":false} },
...
]
}
Each type of message has its own expected args. For example:
class TypeAMessage extends Message {
String a;
int b;
}
class TypeBMessage extends Message {
boolean c;
boolean d;
}
I could map this JSON to a simple POJO like:
class Messages {
@JsonProperty("user")
String user;
@JsonProperty("messageList")
List<Message> messageList;
class Message {
@JsonProperty("type")
String type;
@JsonProperty("args")
Map<String, Object> args;
}
}
But this doesn't seem ideal, because args can contain multiple variable types (String, Integer, ...) and now they're all being stored as a general Object variable.
I already know what args to expect based on the message type. Since each type expects a different set of arguments, I thought of mapping the JSON to a class like this:
class Messages {
@JsonProperty("user")
String user;
@JsonProperty("messageList")
List<? extends Message> messageList;
class Message {}
class TypeAMessage extends Message {
@JsonProperty("a")
String a;
@JsonProperty("b")
int b;
}
class TypeBMessage extends Message {
@JsonProperty("c")
boolean c;
@JsonProperty("d")
boolean d;
}
}
I'm using Jackson JSON, and JSON-to-object conversion fails with Unrecognized field "a" (and b, c, d too) because these fields are not in the parent Message class.
Am I going about this the wrong way? Or is there a way to contain each Message Child object, by telling the JSON Object Mapper to look for children to map to?