DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • Building Modern 3factor Apps in 2021 With Event-Driven Programming
  • How to Introduce a New API Quickly Using Micronaut
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API

Trending

  • Supervised Fine-Tuning (SFT) on VLMs: From Pre-trained Checkpoints To Tuned Models
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  1. DZone
  2. Data Engineering
  3. Databases
  4. Getting Started With JSON-B and Yasson

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.

By 
Ehsan Zaery Moghaddam user avatar
Ehsan Zaery Moghaddam
·
Updated Dec. 22, 16 · Opinion
Likes (1)
Comment
Save
Tweet
Share
12.2K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Reference implementation API

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

Opinions expressed by DZone contributors are their own.

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • Building Modern 3factor Apps in 2021 With Event-Driven Programming
  • How to Introduce a New API Quickly Using Micronaut
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!