Getting started with JSON-B

Java API for JSON Binding or JSON-B is one of the newest APIs that’s going to be a part of Java EE 8 and has already passed the Public Review Ballot. As you may guess from its name, the JSON-B is trying to standardize the way Java objects would be serialized (presented) in JSON and defines a standard API in this regards. 

In this post, I’ll try to demonstrate core features and functionalities provided by this API so that you can have an idea about how to utilize it in your next project.

What you’ll learn in this post?

  • Setting up a project to use JSON-B
  • Reference Implementation of JSON-B
  • Serializing/Deserializing an object to/from JSON
  • The way primitive data types are mapped
  • Serializing Collection and Map implementation

Setup project dependencies

Currently the artifact containing the JSON-B API (javax.json.bind-api-1.0-SNAPSHOT.jar) is hosted on maven.java.net repository. Also the only reference implementation of JSON-B API (named “yasson“) has a dedicated snapshot repository hosted on repo.eclipse.org. So in order to have these artifacts defined as a dependency in your pom file, you have to add these repositories to your pom.xml.

Note:

As Yasson (JSON-B reference implementation) internally relies on JSON-P API, a dependency to JSON-P reference implementation is added to the classpath. This may not be needed if you use another implementation of JSON-B in future or if you’re going to deploy your application on an application server that already provides this dependency at runtime.

JSON-B API

The JSON-B APIs are provided under javax.json.bind package. The most important interface is Jsonb that could be instantiated through a builder class named JsonbBuilder. When you have a reference to this class, you can call one of toJson or fromJson methods to serialize/deserialize objects to/from JSON string.

Note that, for the deserialization process, the class should have a default constructor or else you’ll get an exception.

That’s it. The surface area of the JSON-B API is so small that there is almost no complexity involved. All other APIs and annotations provided under ‘javax.jsonb’ package (which are few in number) are only used for customizing the serialization/deserialization process.

Basic Java types mapping

The way Java primitive types and their corresponding wrapper classes are serialized to JSON, follows the conversion process defined for their ‘toString’ method documentation. Likewise, for the deserialization process, the conversion process defined for their ‘parse[TYPE]’ method (parseInt, parseLong, etc.) is used. However it’s not necessary for a reference implementation to call such methods, just to obey their conversion process.

To demonstrate how these types are mapped to JSON, consider a class named Apartment with following structure:

Following snippet tries to serialize an instance of this class.

which results to following JSON in output (comments are added to make it more readable):

As can be seen, the value used for each field is exactly the same as calling ‘toString’ method on its corresponding wrapper class. Also the String and Character classes are both converted to a UTF-8 string.

Mapping Dates

JSON-B spec defines a standard mapping for almost all the date and time related classes in JDK. The formats are based on ISO 8601. Parsing and formatting date values based on this ISO standard are already implemented in JDK in java.time.format.DateTimeFormatter. In a class definition that follows, you can find a property for every date and time classes defined in JDK along with its corresponding serialization format used in JSON-B:

We can instantiate and serialize an instance of this class as below:

Which results in the following JSON:

Note that the order of properties in the output would not necessarily be the same as the one in the code. I’ve changed the order of properties in the above JSON fragment to be the same as its corresponding code snippet to make it easier to read and compare with its corresponding code. However you can customize the ordering of properties in the output by JSON-B annotations. Also I’ve aligned the values to make them more readable.

Mapping Collections

JSON-B has a comprehensive support for almost all collection and map classes available in java.util as long as they provide a default no-argument constructor. Map based classes (e.g HashMap, TreeMap, NavigableMap, etc. that implement java.util.Map interface) would be serialized as an object that its properties correspond to map keys and have their values from the map. Classes extending from java.util.Collection (e.g. Set, List, HashedSet, LinkedList, ArrayList, etc.) are mapped to JSON arrays on the output.

In the following snippet, the Blog class has a set of Post objects and each Post has a map of comments in which the name of the person who made the comment is the key and the comment text is the value.

No if we try to instantiate and initialize a Blog as follow:

The final output would be:

As can be seen, empty the posts property is mapped to a JSON array of objects in which each object has a comments property that is generated from the map. For the “Third post”, as there is no comment, the map is serialized as an empty object (a pair of {}). This is due to the fact that the Map property inside Post class is always initialized to an empty HashMap and it’s not a null.

Conclusion

JSON-B is one of the first JSRs (among those that supposed to be part of Java EE 8) that its specification is almost ready and its only RI (Yeasson) is fully implemented. Now its time to polish it, stabilize it and make it ready to be integrated in different projects, frameworks and application servers. This was just a short review of some basic features of this JSR. For more information please visit www.json-b.net.

6 thoughts on “Getting started with JSON-B

  1. Greetings from California! I’m bored to tears at work so
    I decided to browse your website on my iphone during lunch break.

    I enjoy the info you present here and can’t wait to take a look when I get home.
    I’m shocked at how quick your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyhow, good site!

  2. Pingback: Java EE Recap | Subremes Codes
  3. I will right away snatch your rss as I can’t find
    your email subscription link or e-newsletter service. Do you have any?
    Please permit me recognise so that I could subscribe. Thanks.

Leave a Reply

Your email address will not be published.