• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3556
  • Last Modified:

Converting Json to HashMap

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.

Rohit Bajaj
Rohit Bajaj
  • 2
1 Solution
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.
Rohit BajajAuthor Commented:
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();
        ArrayList list = new ArrayList();
           VelocityContext context = new VelocityContext();
       context.put("beingList", list);
            Template t = ve.getTemplate( "src\\sample.vm" );
              StringWriter writer = new StringWriter();
       t.merge( context, writer );
-------------------------------VELOCITY CODE ENDS---------------------------------------

Now after converting the jsonstring to hashmap if i use the following in the velocity .vm file :
  #foreach( $b in $beingList )
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
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...

... or ...


Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now