Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

parsing

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?

like image 640
ekeen4 Avatar asked Sep 30 '16 08:09

ekeen4


People also ask

What is javax JSON?

The javax. json package provides an Object Model API to process JSON. The Object Model API is a high-level API that provides immutable object models for JSON object and array structures. These JSON structures can be represented as object models using JsonObject and JsonArray interfaces.

How do I read a JSON file in REST API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.

What is JSON reader?

android.util.JsonReader. Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays.


1 Answers

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

like image 78
Andrii Abramov Avatar answered Nov 01 '22 08:11

Andrii Abramov