im using jackson to deserialize some Json. I am reading through a large json document and pulling out blocks and telling jackson to take that block and deserialize it to an object that I created (Actually several objects as there are nested arrays) in java to match the json.
The code im using to deserialize is
fooObject newFoo = mapper.readValue(newNode,fooObject.class);
The problem is there is a value in the block that is sometimes a hash such as
addWidgetStrategy={"get":2,"spend":6,"textLabel":"bikes"}
and sometimes an array
addWidgetStrategy=[{"get":1.5,"spend":3,"textLabel":"thursday"},{"get":3,"spend":5,"textLabel":"tuesday"}]
So in fooObject I need to deal with addWidgetStrategy which has its own object. If in fooObject I put
public addWidgetStrategy addWidgetStrategy;
The above works until it tried to deserialize an array
If I put
public List<addWidgetStrategy> addWidgetStrategy;
it works just for arrays and blows up when its just a single hash
How can I parse that same Json element addWidgetStrategy regardless if its an array or a single hash?
For arrays it should be:
fooObject[] newFoo = mapper.readValue(newNode,fooObject[].class);
You can read it like this:
JsonNode jsonNode = mapper.readTree(json);
if (jsonNode.isArray()) {
fooObject[] newFoo = mapper.readValue(jsonNode,fooObject[].class);
...
} else {
fooObject newFoo = mapper.readValue(jsonNode,fooObject.class);
....
}