1

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?

1 Answer 1

2

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);  
       ....
   }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.