Converting Json to HashMap

Hi,
I need to convert a json string into hashmap.
I used the following code which uses jackson parser internally :
HashMap<String,Object> result = new ObjectMapper().readValue(jsonString, HashMap.class);

when jsonString  = "{\"being\":{\"name\":\"robin\",\"age\": 28}}"
This perfectly converts into a proper hashMap.

But when jsonString = "[{\"mnArr\":[{\"dd\":\"26/09/2013\",\"cf\":[{\"tf\":\"8825\"}]}]}]";

This line errors out with following error message in console :

---------------------
Exception in thread "Main Thread" org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
 at [Source: java.io.StringReader@20c98c4; line: 1, column: 1]
      at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:153)
      at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:131)
      at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:69)
      at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:59)
      at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:22)
      at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:651)
      at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:445)
      at Test.main(Test.java:30)
------------------

 Both the jsons i validated on http://jsonlint.com/ are valid.
I am unable to find out the reason why one is getting converted into hashMap properly and other is getting errored out.

Thanks
Robin
Rohit BajajAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
See the square brackets, [ and ], around the entire string? They indicate an array in JSON terms. So in deciphering that JSON string you would say this... it is an array that only has 1 element which is an object with a field called "mnArr" whose value is an array which has 1 element...... and so on.

So to map that correctly use this...
List<?> result = new ObjectMapper().readValue(jsonString, List.class);

Open in new window

If you want to ALWAYS return a Map (and you probably should use Map rather than HashMap) you could wrap your string in a JSON wrapper object as such...
Map<String, Object> result = new ObjectMapper().readValue("{\"root\":" + jsonString + "}", Map.class);

Open in new window

The above code will work with either jsonstring that you presented in your original question.
0
Rohit BajajAuthor Commented:
Hi,
Thanks for the solution. It works. I want to add one another thing to the question:

when jsonString  = "{\"being\":{\"name\":\"robin\",\"age\": 28}}"
---------------------------------------------------------------------VELOCITY CODE------------------
VelocityEngine ve = new VelocityEngine();
        ve.init();
        ArrayList list = new ArrayList();
list.add(result);
           VelocityContext context = new VelocityContext();
       context.put("beingList", list);
            Template t = ve.getTemplate( "src\\sample.vm" );
              StringWriter writer = new StringWriter();
       t.merge( context, writer );
       System.out.println(writer.toString());
-------------------------------VELOCITY CODE ENDS---------------------------------------

Now after converting the jsonstring to hashmap if i use the following in the velocity .vm file :
  #foreach( $b in $beingList )
   $b.root.being.name
#end
This properly prints the value "robin"

But when jsonString = "[{\"mnArr\":[{\"dd\":\"26/09/2013\",\"cf\":[{\"tf\":\"8825\"}]}]}]";
and if i use $b.root.mnArr.dd  the value in date does not get printed.

I want to use the json constructed hashmap in velocity.

Please advice
thanks
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
The problem is because of what I stated in the previous comment. That second JSON string is actually an array/list of objects that contain an array/list of objects.... etc, etc.

I haven't actually used velocity but knowing that they are arrays (or lists, once they are in Java), my guess is that you would do something like...
$b.root[0].mnArr[0].dd

... or ...

$b.root.get(0).mnArr.get(0).dd

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.