Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Getting Started With JSON-B and Yasson

DZone's Guide to

Getting Started With JSON-B and Yasson

JSON-B is one of the newest APIs for Java EE 8. It helps standardize how Java objects are serialized in JSON.

Free Resource

Share, secure, distribute, control, and monetize your APIs with the platform built with performance, time-to-value, and growth in mind. Free 90-day trial of 3Scale by Red Hat

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. It has already passed the Public Review Ballot. As you may guess from its name, 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.

Set Up Project Dependencies

Currently, the artifact containing the JSON-B API (javax.json.bind-api-1.0-SNAPSHOT.jar) is hosted on a 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.

<dependencies>
    <dependency>
        <groupId>javax.json.bind</groupId>
        <artifactId>javax.json.bind-api</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>                
    <dependency>
        <groupId>org.eclipse</groupId>
        <artifactId>yasson</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.json</artifactId>
        <version>1.1.0-SNAPSHOT</version>
    </dependency>
</dependencies>
<repositories>
    <!-- Needed for JSON-B API -->
    <repository>
        <id>java.net-Public</id>
        <name>Maven Java Net Snapshots and Releases</name>
        <url>https://maven.java.net/content/groups/public/</url>
    </repository>

    <!-- Needed for Yasson -->
    <repository>
        <id>yasson-snapshots</id>
        <name>Yasson Snapshots repository</name>
        <url>https://repo.eclipse.org/content/repositories/yasson-snapshots</url>
    </repository>
</repositories>

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

JSON-B APIs are provided under the 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 and deserialize objects to and from the JSON string.

Shape shape = new Shape();
shape.setArea(12);
shape.setType("RECTANGLE");


Jsonb jsonb = JsonbBuilder.create();

// serialize an object to JSON
String jsonString = jsonb.toJson(shape); // output : {"area" : 12, "type" : "RECTANGLE"}

// deserialize a JSON string to an object
Shape s = jsonb.fromJSON("{\"area\" : 12, \"type\": \"TRIANGLE\"}");

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 the javax.jsonb package (which are few in number) are only used for customizing the serialization and 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:

public class Apartment {

    private boolean rented;
    private byte rooms;
    private int price;
    private long id;
    private float loan;
    private double area;
    private char district;
    private String ownerName;

    /** getter and setters */
}

The following snippet tries to serialize an instance of this class:

public static void main(String[] args) {

    Apartment apartment = new Apartment();
    apartment.setRented(true);
    apartment.setRooms((byte) 4);
    apartment.setPrice(7800000);
    apartment.setId(234L);
    apartment.setLoan(3580000.4f);
    apartment.setArea(432.45);
    apartment.setDistrict('S');
    apartment.setOwnerName("Nerssi");

    String apartmentJSON = jsonb.toJson(apartment);
    System.out.printf(apartmentJSON);
}

This results in the JSON output shown below (comments are added to make it more readable):

{
    "area":432.45,        // double
    "district":"S",       // char
    "id":234,             // long
    "loan":3580000.5,     // float
    "ownerName":"Nerssi", // String
    "price":7800000,      // int
    "rented":true,        // boolean
    "rooms":4             // byte
}

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.

Explore the core elements of owning an API strategy and best practices for effective API programs. Download the API Owner's Manual, brought to you by 3Scale by Red Hat

Topics:
json ,integration ,yasson ,jave ee 8

Published at DZone with permission of Ehsan Zaery Moghaddam. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}