4

我正在尝试递归解析具有许多复杂元素集的示例 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)):期望双引号在 [Source: java.io.StringReader@2de7753a; 开始字段名称;行:1,列:3]

实际上,我想做的是解析文件并获取名称对象对的列表,然后获取具有名称对象对的对象。- 但问题是解析器在字符串之前期待“”!

4

2 回答 2

5

Instead of parsing everything by yourself you should consider to use Jacksons built-in tree model feature (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());
    …

}

This should be more convenient in the long run. Have a look at the API at http://fasterxml.github.com/jackson-databind/javadoc/2.1.0/com/fasterxml/jackson/databind/JsonNode.html.

于 2013-03-18T18:46:12.273 回答
4

Just a comment. As you know there are 3 major processing modes that Jackson supports (Data Binding, Streaming API and Tree Model). You need to take into account that if you decide to use the Tree Model, acording to the official docs, the memory usage is proportional to content mapped (similar to data binding), so tree models can NOT be used with huge Json content, unless mapping is done chunk at a time. This is the same problem that data binding encounters; and sometimes the solution is to use Stream-of-Events instead.

于 2014-04-29T09:21:22.340 回答