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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With