我试图以递归方式解析具有许多复杂元素集的示例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
}
}
}}
Run Code Online (Sandbox Code Playgroud)
我得到这个例外:
异常org.codehaus.jackson.JsonParseException:意外字符('i'(代码105)):期望双引号在[来源:java.io.StringReader@2de7753a; line:1,column:3]
实际上我想要做的是,解析文件并获取名称对象对列表,并获取inturn具有名称 - 对象对的对象. - 但问题是解析器在字符串之前期待""!
您应该考虑使用Jacksons内置树模型功能(http://wiki.fasterxml.com/JacksonTreeModel),而不是自己解析所有内容:
ObjectMapper mapper = new ObjectMapper(factory);
File from = new File("D://albumList.txt");
JsonNode rootNode = mapper.readTree(from);
Iterator<Map.Entry<String,JsonNode>> fields = rootNode.fields();
while (fields.hasNext()) {
Map.Entry<String,JsonNode> field = fields.next();
System.out.println(field.getKey() + " = " + field.getValue());
…
}
Run Code Online (Sandbox Code Playgroud)
从长远来看,这应该更方便.请访问http://fasterxml.github.com/jackson-databind/javadoc/2.1.0/com/fasterxml/jackson/databind/JsonNode.html查看API .
| 归档时间: |
|
| 查看次数: |
10029 次 |
| 最近记录: |