Wednesday 28 October 2015

Jackson: JsonParser: Parsing JSON data

In this post, I am going to explain how to parse JSON data using JsonParser.

For example, employee.json contains following data.

{
    "id": "1",
    "firstName": "Hari krishna",
    "lastName": "Gurram",
    "hobbies": [
        "Trekking",
        "Blogging",
        "Cooking"
    ]
}
Following is the step-by-step procedure to parse employee.json file.

Step 1: Instantiate JsonFactory class.
JsonFactory factory = new JsonFactory();

Step 2: Get the JsonParser instance from factory.
JsonParser parser = factory.createParser(new File(filePath));

Step 3: Use parser APIS like nextToken, getText to process the json file.
Following is the complete working application.

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class Main {
    public static void main(String args[]) throws IOException {
        String filePath = "/Users/harikrishna_gurram/employee.json";

        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(new File(filePath));

        while (!parser.isClosed()) {
            JsonToken token = parser.nextToken();

            /* null indicates end-of-input */
            if (token == null)
                break;

            String fieldName = parser.getCurrentName();

            if ("id".equals(fieldName)) {
                parser.nextToken();
                System.out.println(parser.getText());
            } else if ("firstName".equals(fieldName)) {
                parser.nextToken();
                System.out.println(parser.getText());
            } else if ("lastName".equals(fieldName)) {
                parser.nextToken();
                System.out.println(parser.getText());
            } else if ("hobbies".equals(fieldName)) {
                parser.nextToken();
                while (parser.nextToken() != JsonToken.END_ARRAY) {
                    String field = parser.getText();
                    System.out.println(field);
                }
            }
        }

        parser.close();
    }
}


Output
1
Hari krishna
Gurram
Trekking
Blogging
Cooking




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment