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
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
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

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

E-Commerce Development Essentials: Considering starting or working on an e-commerce business? Learn how to create a backend that scales.

Related

  • Hello Woo. Writing Your First Script Using the Woocommerce API
  • Building Modern 3factor Apps in 2021 With Event-Driven Programming
  • Unleashing Conversational Magic: Integrating ChatGPT With React.js and Node.js
  • Maximizing Business Benefits: Building Microservices Architecture in Azure

Trending

  • JBang: How to Script With Java for Data Import From an API
  • Testing Swing Application
  • How to Integrate Istio and SPIRE for Secure Workload Identity
  • Decompose Legacy System Into Microservices: Part 2
  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.

Ehsan Zaery Moghaddam user avatar by
Ehsan Zaery Moghaddam
·
Updated Dec. 22, 16 · Opinion
Like (1)
Save
Tweet
Share
11.3K 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
  • Unleashing Conversational Magic: Integrating ChatGPT With React.js and Node.js
  • Maximizing Business Benefits: Building Microservices Architecture in Azure

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • 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: