How to read a json file in java

Create a txt file named jsondata.txt with the below data


{
    "firstName": "Duke",
    "lastName": "Java",
    "age": 18,
    "streetAddress": "100 Internet Dr",
    "city": "JavaTown",
    "state": "JA",
    "postalCode": "12345",
    "phoneNumbers": [
        { "Mobile": "111-111-1111" },
        { "Home": "222-222-2222" }
    ]
}

Below is the java code which will read the above text file

Main Code


package objectmodel;

import java.io.FileReader;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonStructure;
import javax.json.JsonValue;

public class Example1 {
    public static void main(String[] args) throws Exception {
        JsonReader reader = Json.createReader(new FileReader("jsondata.txt"));
        JsonStructure jsonStructure = reader.read();
        navigateTree(jsonStructure, null);
        reader.close();
    }

    public static void navigateTree(JsonValue tree, String key) {
        switch(tree.getValueType()) {
            case OBJECT:if(key != null) {
                            System.out.println("name: " + key);
                            } else {
                            System.out.println("name: Parent Object");
                        }
                        JsonObject object = (JsonObject) tree;
                        for(String name : object.keySet()) {
                        navigateTree(object.get(name), name);
                        }
                        break;
            case ARRAY: JsonArray array = (JsonArray) tree;
                        for(JsonValue value : array) {
                        navigateTree(value, key);
                        }
                        break;
            case STRING:JsonString jsonString = (JsonString) tree;
                        System.out.println("name: " + key + " value: " + jsonString.getString());
                        break;
            case NUMBER:JsonNumber jsonNumber = (JsonNumber) tree;
                        System.out.println("name: " + key + " value: " + jsonNumber.toString());
                        break;
        }
    }
}

Output

name: Parent Object
name: firstName value: Duke
name: lastName value: Java
name: age value: 18
name: streetAddress value: 100 Internet Dr
name: city value: JavaTown
name: state value: JA
name: postalCode value: 12345
name: phoneNumbers
name: Mobile value: 111-111-1111
name: phoneNumbers
name: Home value: 222-222-2222

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s