5

我有一小段代码,我正在尝试将 JSON 字符串转换为地图。

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>>() { });

但它返回以下错误:

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)

我究竟做错了什么?

4

2 回答 2

6

据我所知,Jackson 用于将 json 转换为 java 类 - 它可能期望第一个对象被读取为地图,例如

String json = "{'code':':)','img':'<img src=/faccine/sorriso.gif>'}";
于 2011-02-16T15:47:58.947 回答
4

对:您要求 Jackson 将 JSON 数组映射到对象;没有明显的方法可以做到这一点。所以,托法尔的回答是正确的。

但是如果你想要一个 List 或一个数组,你可以通过以下方式轻松实现:

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

或带有完整的类型参考;在这种情况下是可选的,因为您只需要列表、地图和字符串。

于 2011-02-18T18:19:58.047 回答