Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively parsing a json file using Jackson Json parser

Tags:

json

jackson

I'm trying to recursively parse a sample Json file that has many sets of complex elements. And the code that i'm trying is this :

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



    }   
    }
}}

and i get this exception :

Exception org.codehaus.jackson.JsonParseException: Unexpected character ('i' (code 105)): was expecting double-quote to start field name at [Source: java.io.StringReader@2de7753a; line: 1, column: 3]

Actually what im trying to do is, parse the file and get list of name object pairs, and take the object which inturn has name-object pairs. - but the problem is that the parser is expecting "" before strings !

like image 927
sreeraag Avatar asked Jan 14 '23 22:01

sreeraag


1 Answers

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.

like image 134
nutlike Avatar answered Feb 21 '23 16:02

nutlike