6

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:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.HashMap out of START_ARRAY token
 at [Source: java.io.StringReader@1b1756a4; line: 1, column: 1]
    at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
    at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:198)
    at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:151)
    at org.codehaus.jackson.map.deser.MapDeserializer.deserialize(MapDeserializer.java:25)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2131)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1402)
    at CodeSnippet_19.run(CodeSnippet_19.java:13)
    at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain1.eval(ScrapbookMain1.java:20)
    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(ScrapbookMain.java:54)
    at org.eclipse.jdt.internal.debug.ui.snippeteditor.ScrapbookMain.main(ScrapbookMain.java:35)

What am I doing wrong?

Pang
  • 9,564
  • 146
  • 81
  • 122
Laphroaig
  • 619
  • 4
  • 12
  • 26

2 Answers2

6

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>'}";
tofarr
  • 7,682
  • 5
  • 22
  • 30
  • ok now it work but i have to use doublequote like this: String json = "{\"code\":\":)\",\"img\":\"\"}"; – Laphroaig Feb 16 '11 at 16:03
  • Yes, JSON requires double-quotes for property names (although some parser, including Jackson, allow non-standard modes which can loosen restrictions) – StaxMan Feb 18 '11 at 18:17
4

Right: you're asking Jackson to map a JSON Array into an object; there is no obvious way to do that. So, tofarr's answer is correct.

But if you wanted a List or an array, you could achieved it easily by:

List<?> list = mapper.readValue(json, List.class);

Or with full type reference; optional in this case because you just want Lists, Maps and Strings.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
StaxMan
  • 113,358
  • 34
  • 211
  • 239