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:

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:

We can create a JsonObject from the JSON by using JsonReader object as follows:

2.3. Create a JsonObject object from scratch

Let’s say we have an JSON string as below:

Here is the source code we can implement to create a JsonObject object from scratch:

2.4. Create a JsonObject object from file

Let’s assume that we have a contacts.json with content as the below:

Here is the source code we can use to create a JsonObject instance from this file by using the JsonReader object:

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.

The output will be:

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.

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:

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.

0 0 vote
Article Rating