In this tutorial, we will show you how to use the JsonObject class, a part of the Java API for JSON processing, to read and write JSON data from/to string, file and stream.
1. Introduction to the JsonObject class
The JsonObject class which is a part of the Java API for JSON Processing (JSR 353) , has following attributes:
- Represents an immutable JSON object value.
- Provides a unmodifiable Map view of the JSON object. This means we can access its properties in key/value or name/value style.
- Can be created from an input source using the JsonReader.readObject() method.
- Or can also be built from scratch using the JsonObjectBuilder class.
2. JsonObject Example
2.1. Preparation
There are several libraries implements Java API for JSON Processing (JSR-353) such as: JSON-P, Moxy, JSON-java. However, in this tutorial, we are going to use JSON-P, a reference implementation from the Java community. Hence, to prepare for the following examples, we have to add 2 dependencies below to the class path of our application:
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- API --> <dependency> <groupId>javax.json</groupId> <artifactId>javax.json-api</artifactId> <version>1.0</version> </dependency> <!-- Implementation --> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.0.4</version> </dependency> |
The sample source code can be download here: example source.zip
2.2. Create a JsonObject object from JSON string
Let’s assume that we have a JSON string which represents a contact in the contact list of our smartphone:
1 2 3 4 5 6 |
{ "firstName":"Maria", "lastName":"Johnson", "phoneNumber":"(541) 754-3010", "notes":"FTA Project." } |
We can create a JsonObject from the JSON by using JsonReader object as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Test public void testCreateJsonObjectFromString() { JsonReader jsonReader = Json .createReader(new StringReader("{\"firstName\":\"Maria\",\"lastName\":\"Johnson\"," + "\"phoneNumber\":\"(541) 754-3010\",\"notes\":\"FTA Project.\"}")); // create an instance from string JsonObject jsonObj = jsonReader.readObject(); jsonReader.close(); assertEquals("Maria", jsonObj.getString("firstName")); assertEquals("Johnson", jsonObj.getString("lastName")); assertEquals("(541) 754-3010", jsonObj.getString("phoneNumber")); assertEquals("FTA Project.", jsonObj.getString("notes")); String ts = jsonObj.toString(); System.out.println(ts); } |
2.3. Create a JsonObject object from scratch
Let’s say we have an JSON string as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "firstName":"Maria", "lastName":"Johnson", "phoneNumber":"(541) 754-3010", "notes":"FTA Project.", "emails":[ { "type":"home", "email":"mariajohson@gmail.com" }, { "type":"work", "email":"mariajohson@company.com" } ] } |
Here is the source code we can implement to create a JsonObject object from scratch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
@Test public void testCreateJsonObjectFromScratch() { JsonObject jsonContact = Json.createObjectBuilder() .add("firstName", "Maria") .add("lastName", "Johnson") .add("phoneNumber", "(541) 754-3010") .add("notes", "FTA Project.") .add("emails", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("email", "mariajohson@gmail.com")) .add(Json.createObjectBuilder() .add("type", "work") .add("email", "mariajohson@company.com"))) .build(); assertEquals("Maria", jsonContact.getString("firstName")); assertEquals("Johnson", jsonContact.getString("lastName")); assertEquals("(541) 754-3010", jsonContact.getString("phoneNumber")); assertEquals("FTA Project.", jsonContact.getString("notes")); JsonArray emails = jsonContact.getJsonArray("emails"); JsonObject homeEmailJO = emails.getJsonObject(0); JsonObject workEmailJO = emails.getJsonObject(1); // home email assertEquals("home", homeEmailJO.getString("type")); assertEquals("mariajohson@gmail.com", homeEmailJO.getString("email")); // work email assertEquals("work", workEmailJO.getString("type")); assertEquals("mariajohson@company.com", workEmailJO.getString("email")); } |
2.4. Create a JsonObject object from file
Let’s assume that we have a contacts.json with content as the below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "firstName":"Maria", "lastName":"Johnson", "phoneNumber":"(541) 754-3010", "notes":"FTA Project.", "emails":[ { "type":"home", "email":"mariajohson@gmail.com" }, { "type":"work", "email":"mariajohson@company.com" } ] } |
Here is the source code we can use to create a JsonObject instance from this file by using the JsonReader object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
@Test public void testCreateJsonObjectFromFile() throws FileNotFoundException { File file = new File(getClass().getClassLoader().getResource("contacts.json").getFile()); JsonReader jsReader = Json.createReader(new FileReader(file)); // create JsonObject instance JsonObject jsObj = jsReader.readObject(); jsReader.close(); assertEquals("Maria", jsObj.getString("firstName")); assertEquals("Johnson", jsObj.getString("lastName")); assertEquals("(541) 754-3010", jsObj.getString("phoneNumber")); assertEquals("FTA Project.", jsObj.getString("notes")); JsonArray emails = jsObj.getJsonArray("emails"); JsonObject homeEmailJO = emails.getJsonObject(0); JsonObject workEmailJO = emails.getJsonObject(1); // home email assertEquals("home", homeEmailJO.getString("type")); assertEquals("mariajohson@gmail.com", homeEmailJO.getString("email")); // work email assertEquals("work", workEmailJO.getString("type")); assertEquals("mariajohson@company.com", workEmailJO.getString("email")); } |
Note that the contacts.json file is put in the src/test/resources/ folder.
2.5. Convert a JsonObject object to string
Here is an JsonObject example that we build a JsonObject object from the scratch and then convert it to a JSON string by calling its toString() method.
1 2 3 4 5 6 7 8 |
JsonObject jsonMovie = Json.createObjectBuilder() .add("name", "The Dark Knight") .add("year", "2008") .add("rate", "9.0") .add("director", "Christopher Nolan") .add("reviews", "4720").build(); System.out.println(jsonMovie.toString()); |
The output will be:
1 |
{"name":"The Dark Knight","year":"2008","rate":"9.0","director":"Christopher Nolan","reviews":"4720"} |
2.6. Write a JsonObject object to file
In this example, we create a JsonObject object from the src/test/resources/contacts.json file and then write it to the d:/contacts_out.json file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Test public void testWriteJsonObjectToFile() throws IOException { File file = new File(getClass().getClassLoader().getResource("contacts.json").getFile()); JsonReader jsonReader = Json.createReader(new FileReader(file)); // create new instance JsonObject jsnObject = jsonReader.readObject(); jsonReader.close(); // Write back to jsonObject to file. JsonWriter jsonWriter = Json.createWriter(new FileWriter("d:/contacts.json")); jsonWriter.writeObject(jsnObject); jsonWriter.close(); // check file here } |
2.6. Other functions of JsonObject
The JsonObject class allows us to specify the JSON data types such as: number, string, boolean, array, etc when we build and access its properties. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Test public void testJsonObjectMethods() throws IOException { JsonObject jsonMovie = Json.createObjectBuilder() .add("movieName", "The Godfather") .add("year", 1972) .add("rate", 9.2) .add("director", "Francis Ford Coppola") .add("reviews", 2280) .add("checked", true) .build(); //Get integer value assertEquals(1972,jsonMovie.getInt("year")); //Get double value assertEquals(9.2,jsonMovie.getJsonNumber("rate").doubleValue()); //Get boolean value Assert.assertTrue(jsonMovie.getBoolean("checked")); //Get String value assertEquals("The Godfather",jsonMovie.getString("movieName")); } |
3. Summary
We have just gotten familiar with Java API for JSON processing by getting started with JsonObject class. We also got through some related examples which each of them is a JsonObject example may cover basic usecases such as: create JsonObject from a string, a file, a stream or even from scratch and write it back to a file or a stream as well. Finally, there are many implementations of the Java API for Json Processing as mentioned on the top of the article, you can select the most suitable one for your purpose.