Say I have a JSON file that looks like this:
{
"response" : [
{
"id" : "10",
"period" : "month",
"values" : [
{
"value" : 100,
"date" : "2013-05-10"
}
],
"parent" : "1"
},
{
"id" : "10",
"period" : "day",
"values" : [
{
"value" : {
"foo" : 10,
"bar" : 11,
"etc" : 4
},
"date" : "2013-05-10"
}
],
"parent" : "1"
},{
"id" : "13",
"period" : "year",
"values" : [
{
"value" : {
"info" : 1,
"pages" : 10,
"etc" : 4
},
"date" : "2013-05-10"
}
],
"parent" : "1"
}
]
}
Notice the 'values' part can either be a single value, or an object (which is unique).
I want to use the Jackson ObjectMapper to easily map this to a POJO.
What I have so far:
public class Response
{
List<ResponseEntry> response;
/*getters + setters */
public static class ResponseEntry
{
private String id;
private String period;
private String parent;
private List<Value> values;
/*setters + getters*/
public static class Value
{
private Object value;
private String date;
/*setters+getters*/
}
}
}
To map the response, I just specify the file I want and tell ObjectMapper to map to the 'Response' class
ObjectMapper mapper = new ObjectMapper();
Response r = mapper.readValues(json, Response.class);
This works, but is there a better way than just using 'Object' to hold 'value'? Since 'value' can be either a single value or an object, I'm having a bit of difficult figuring out what it should be. I'm certain there is a polymorphic way of handling this, but I've looked and couldn't find anything that worked. I'm pretty stuck and I would appreciate any help.