12

I believe that I will need to create a JsonReader object and call one of the Json static methods, but I am having trouble reading from my file.json.

It seems that the create reader method requires the input to be a string. Should I proceed by trying to get my entire JSON file to be interpreted as a string?

ekeen4
  • 352
  • 1
  • 4
  • 10

1 Answers1

16

Assuming that you have file person.json with such JSON data:

{ 
    "name": "Jack", 
    "age" : 13, 
    "isMarried" : false,
    "address": { 
        "street": "#1234, Main Street", 
        "zipCode": "123456" 
    },
    "phoneNumbers": ["011-111-1111", "11-111-1111"]
}

With javax.json you can parse the file in this way:

public class Example {

    public static void main(String[] args) throws Exception {
        InputStream fis = new FileInputStream("person.json");
     
        JsonReader reader = Json.createReader(fis);
     
        JsonObject personObject = reader.readObject();
     
        reader.close();
     
        System.out.println("Name   : " + personObject.getString("name"));
        System.out.println("Age    : " + personObject.getInt("age"));
        System.out.println("Married: " + personObject.getBoolean("isMarried"));

        JsonObject addressObject = personObject.getJsonObject("address");
        System.out.println("Address: ");
        System.out.println(addressObject.getString("street"));
        System.out.println(addressObject.getString("zipCode"));
     
        System.out.println("Phone  : ");
        JsonArray phoneNumbersArray = personObject.getJsonArray("phoneNumbers");

        for (JsonValue jsonValue : phoneNumbersArray) {
            System.out.println(jsonValue.toString());
        }
    }
}

Also refer to this question: From JSON String to Java Object using javax.json

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
  • Thank you very much. I think I will try using Gson, as it appears to be more powerful. Is there an equivalent in Gson for InputStream fis = new FileInputStream("file.json"); ? – ekeen4 Sep 30 '16 at 14:08
  • @ekeen4 if you need Gson example, please, refer to [Parse JSON file using GSON](http://stackoverflow.com/questions/16377754/parse-json-file-using-gson) – Andrii Abramov Sep 30 '16 at 14:24