Laphroaig Laphroaig - 2 years ago 211
JSON Question

Error converting JSON string to map in Java using Jackson

I have this little piece of code, and I'm trying to convert a JSON string to a map.

String json = "[{'code':':)','img':'<img src=/faccine/sorriso.gif>'}]";
ObjectMapper mapper = new ObjectMapper();
Map<String,String> userData = mapper.readValue(json,new TypeReference<HashMap<String,String>>() { });

But it returns the following error: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
at [Source:; line: 1, column: 1]
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1.eval(
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.evalLoop(
at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.main(

What am I doing wrong?

Answer Source

From what I remember Jackson is used to convert json to java classes - it is probably expecting the first object is reads to be a map, like

String json = "{'code':':)','img':'<img src=/faccine/sorriso.gif>'}";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download