【发布时间】:2019-07-03 13:57:21
【问题描述】:
我正在尝试递归解析一个包含许多复杂元素集的示例 Json 文件。 我正在尝试的代码是这样的:
public class Jsonex {
public static void main(String argv[]) {
try {
Jsonex jsonExample = new Jsonex();
jsonExample.testJackson();
} catch (Exception e){
System.out.println("Exception " + e);
}
}
public static void testJackson() throws IOException {
JsonFactory factory = new JsonFactory();
// System.out.println("hello");
ObjectMapper mapper = new ObjectMapper(factory);
File from = new File("D://albumList.txt");
TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
HashMap<String,Object> o= mapper.readValue(from, typeRef);
// System.out.println("" + o);
Iterator it = o.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
HashMap<String,Object> o1=mapper.readValue(pairs.getValue().toString(),typeRef);
System.out.println("hey"+o1);
Iterator it1 = o1.entrySet().iterator();
while (it1.hasNext()) {
Map.Entry pairs1 = (Map.Entry)it.next();
System.out.println(pairs1.getKey() + " = " + pairs1.getValue());
it1.remove(); // avoids a ConcurrentModificat
}
}
}}
我得到了这个例外:
异常 org.codehaus.jackson.JsonParseException:意外字符('i'(代码 105)):期待双引号开始字段名称 在 [来源:java.io.StringReader@2de7753a;行:1,列:3]
实际上我想做的是,解析文件并获取名称对象对的列表,然后获取具有名称对象对的对象。 - 但问题是解析器在字符串之前期待“”!
【问题讨论】:
-
你能展示一些 JSON 吗?为什么无效?至少对于字段名称,您可以在 ObjectMapper 上配置 JsonParser.Feature ALLOW_UNQUOTED_FIELD_NAMES。
-
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", " onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} } }} 非常感谢,但有一个新的异常。它说异常 org.codehaus.jackson.JsonParseException: Unexpected character ('=' (code 61)): was Expecting a冒号来分隔字段名称和值[来源:java.io.StringReader@2de7753a;行:1,列:5] 现在。请帮助我@nutlike
-
当我询问 JSON 时,我的意思是 您的 JSON,而不是来自 json.org/example.html ...请相应地更新您的问题。除此之外(再次):为什么您的 JSON 无效?你从哪里得到它?
-
这是我实际解析的json文件。我的程序将这个作为输入!
-
好吧,我很困惑,因为所有字段都被正确引用 - 我错过了您代码中的第二个
mapper.readValue(…)。我添加了一个答案,可以帮助您重新思考/重新设计您的解决方案。