Let's 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" } ] }
Note that the “values” part can be either a single value or an object (which is unique).
I want to use ObjectMapper Jackson to easily match this with POJO.
What I still have:
public class Response { List<ResponseEntry> response; public static class ResponseEntry { private String id; private String period; private String parent; private List<Value> values; public static class Value { private Object value; private String date; } } }
To map the response, I simply 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 the "Object" to store the "value"? Since “value” can be either a single value or an object, it’s hard for me to understand what it should be. I'm sure there is a polymorphic way to handle this, but I looked and could not find anything that worked. I am pretty stuck and I would appreciate any help.