An introduction to JSON Processing in Jakarta EE

I introduced you to the JSON Binding specification of Jakarta EE to convert between JSON data and Java objects. To parse, generate, transform, or query JSON data, you can use another Jakarta EE specification, JSON Processing. How is it in details? We will learn together about JSON Processing and its implementation Eclipse Parsson in this tutorial!

First, I will create a new Maven project as an example:

Eclipse Parsson dependency is as follows:

Similar to JSON Binding, you can generate JSON data from a Java object using JSON Processing.

For example, I have a Student class that defines student information as follows:

You can generate JSON data of student information using the write() method of the JsonWriter class, which is initialized from the Json class with the createWriter() method. But to do this, you need to define JSON data with the JsonObject class using the JsonObjectBuilder class first:

Now we will use an implementation of the Writer class like StringWriter to write this student information to JSON data as follows:

Result:

To format the generated JSON string, you can use the JsonWriterFactory class.

This JsonWriterFactory class allows us to configure how we generate the JSON string. We will need a Map object containing configuration information with key and value, then create a new JsonWriterFactory object with this configuration information.

For example, to format the generated JSON string, I will initialize the Map object containing the configuration information first:

Then initialize the JsonWriterFactory object:

Now we will use the createWriter() method of the JsonWriterFactory object instead of the object of the Json class to create a new Writer and write the student information out:

Results when running the example again:

JSON Processing also allows us to convert a JSON data string to a Java object, but the way it works is different from JSON Binding.

We will use the JsonReader object to read the content of JSON data and put it into the JsonObject object.

Then initialize the Student object, and get information about the properties of this Student object from the above JsonObject object as follows:

Result:

I will show you how to query and transform JSON data using JSON Processing in the following tutorials!

Add Comment