Jackson - Multiple Type JSON Processing

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; /*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 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.

+4
source share
1 answer

Unfortunately, with the JSON structure you are processing, the only way to deserialize is to have a value attribute of type Object . However, after JSON deserialization, you can easily determine if value object or a single value.

Please note that JSON only supports five data types: objects (Map in java), arrays, strings, numeric and logical. It looks like in your case, value is likely to be either a number or a map of numbers; then you have two options to check. Using a quick instanceof comparison, you have to figure out what type of value it has.

 ObjectMapper mapper = new ObjectMapper(); Response r = mapper.readValues(json, Response.class); Value val = r.response.get(0).values.get(0); if (val.value instanceof Map) ; // multiple else ; // single 
+3
source

Source: https://habr.com/ru/post/1487404/


All Articles