Home » Java » Java read the end node of large JSON file first

Java read the end node of large JSON file first

Posted by: admin July 12, 2018 Leave a comment

Questions:

I have a large JSON file of approx 65 MB in below format

{
"Root Node": {
    "Node1": {
        "Node1.1": [{
            "logLevel":"INFO"
            "count" : 20
        },{
            "logLevel":"DEBUG"
            "count" : 200
        },{
            "logLevel":"ERROR"
            "count" : 2000
        }],
        "Node1.2": "",
        "Node1.3": {
            "fromDate": "2014-11-11T14:59:59",
            "toDate": "2014-11-11T14:00:00"
        }
    }
}

}

I am using Jackson to parse the large file I want to read the node Node1.3
then read Node1.1 and create an POJO object which will have all the data from Node1.1 Array and with each data the fromDate and toDate will be associated. I can parse the file if i go in a sequential manner but the Node1.3 is read at the end.

I am Using Below Code to parse the File

public class TempMain {

public static void main(String [] args) throws IOException, ParseException {
    JsonFactory jfactory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper();

    try(JsonParser jParser = jfactory.createParser(new File("/tmp/file.json"))) {
        // loop until token equal to "}"
        while (jParser.nextToken() != com.fasterxml.jackson.core.JsonToken.END_OBJECT) {
            String fieldname = jParser.getCurrentName();
            jParser.nextFieldName();

            if ("Node1.1".equals(fieldname)) {
                /** current token is "[", move next messages is array, loop until token equal to "]"
                 **/
                jParser.nextToken();
                while(jParser.nextToken() == com.fasterxml.jackson.core.JsonToken.START_OBJECT) {
                    // read everything from this START_OBJECT to the matching END_OBJECT
                    // and return it as a tree model ObjectNode
                    ObjectNode node = mapper.readTree(jParser);

                    // Logic to process the data

                }
            }
        }
        jParser.close();
    } catch(Exception e) {
       e.printStackTrace();
    }
}

}

Answers: