deserializing json with arrays

Go To


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


and sometimes an array


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?

2012-04-04 19:06
by ducati1212


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);  
2012-04-11 21:22
by Eugene Retunsky