Java:将JSON结构反序列化为Map< String,Object> [英] Java: Deserializing JSON structure to Map<String, Object>
问题描述
我用于测试的示例字符串是:
code> {\ cases\ :[{\ documents\ :[{\ files\ :[{\ name\ :\ 一个。 pdf\}]}]}]}
这应该读作一系列案例每个都有一系列文件,每个文件都有一个文件数组,每个文件都有一个名字
我尝试过Google的Gson,但是
Gson gson = new Gson();
列表< Map< String,Object>> results = gson.fromJson(dictString,List.class);
给我:
com.google.gson.JsonParseException:JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@561777b1无法反序列化json对象{case:[{documents:[{files:[ {name:a.pdf}]}]}]}给定类型接口java.util.List
我试过Jackson,但是
列表< Map< String,Object>> result =(List< Map< String,Object>)new ObjectMapper()。readValue(dictString,List.class);
给了我:
org.codehaus.jackson.map.JsonMappingException:无法反序列化java.util.List中的实例,从[OBJECT令牌
] [Source:java.io.StringReader@1c5aebd9;行:1,列:1]
你有什么建议吗?或者是为了正确使用上述任何一种,还是给我需要的另一个解析器?
干杯
Nik
根据您的描述,这听起来像您的定义不匹配。它像这样的东西应该是这样的:列表<列表< String>>>
更多的手册,但看看这里:
这将给你一个比自己解析字符串更容易使用的JSONObject,但是你仍然必须钻入它并手动构建您的地图。一半半解决方案。
I've got a JSON string that I want to convert to a Map structure where Object is either a Java version of a basic type (i.e. String, Int, Double), a Map. or a List.
The sample string I'm using for my tests is:
"{\"cases\":[{\"documents\":[{\"files\":[{\"name\":\"a.pdf\"}]}]}]}"
This should read as an array of cases that each have an array of documents, that each have an array of files, that each have a name
I've tried Google's Gson, but
Gson gson = new Gson();
List<Map<String, Object>> results = gson.fromJson(dictString, List.class);
gives me:
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter@561777b1 failed to deserialize json object {"cases":[{"documents":[{"files":[{"name":"a.pdf"}]}]}]} given the type interface java.util.List
and I tried Jackson, but
List<Map<String, Object>> results = (List<Map<String, Object>>) new ObjectMapper().readValue(dictString, List.class);
gave me:
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.List out of START_OBJECT token
at [Source: java.io.StringReader@1c5aebd9; line: 1, column: 1]
Do you have any suggestions? Either for how to use either of the above correctly, or for another parser that gives me what I want?
Cheers
Nik
Given your description, it sounds like your definition doesn't match up. It dounds like it should be something like: List<List<list<String>>>
It's a bit more manual but have a look here:
This will give you a JSONObject that is much easier to use than parsing the string yourself, but you will still have to drill into it and manually build your map. Kind of a half and half solution.
这篇关于Java:将JSON结构反序列化为Map< String,Object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!