ekeen4 ekeen4 - 4 months ago 19
JSON Question

How can I read from a JSON file using the javax.json package?

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?


Assume that you have file file.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 this file is this way:

public class Example throws Exception {

    public static void main(String[] args) {
        InputStream fis = new FileInputStream("file.json");

        JsonReader reader = Json.createReader(fis);

        JsonObject personObject = reader.readObject();


        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("Phone  : ");
        JsonArray phoneNumbersArray = personObject.getJsonArray("phoneNumbers");

        for (JsonValue jsonValue : phoneNumbersArray) {

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