{ "Getting" : "started" }

This is a quick Getting Started guide showcasing the basic JSON-B operations.

Add Dependencies

Add the following repositories to your Maven project:

<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>
</repositories>

Add the following dependencies:

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>
                    
<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Mapping an object

The main JSON-B entry point is Jsonb class. It provides all necessary methods to serialize and deserialize Java objects. Jsonb instances are thread safe. They can be cached and reused.

public class Dog {
    public String name;
    public int age;
    public boolean bitable;
}

// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bitable = false;

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);

// Deserialize back
dog = jsonb.fromJson("{\"age\":4,\"bitable\":false,\"name\":\"Falco\"}", Dog.class);

Mapping a collection

JSON-B supports collections and generic collections handling. For proper deserialization the runtime type of resulting object needs to be passed to JSON-B during deserialization. It can be done a way shown below.

// List of dogs
List<Dog> dogs = new ArrayList<>();
dogs.add(falco);
dogs.add(cassidy);

// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dogs);

// Deserialize back
dogs = jsonb.fromJson(result, new ArrayList<Dog>(){}.getClass().getGenericSuperclass());

Customized mapping

Your mappings can be customized in many different ways. You can use JSON-B annotations for compile time customizations and JsonbConfig class for runtime customizations. The sample below shows a creation of custom configuration serializing null values (by default class properties with null values are skipped).

// Create custom configuration
JsonbConfig nillableConfig = new JsonbConfig().withNullValues(true);

// Create Jsonb with custom configuration
Jsonb jsonb = JsonbBuilder.create(nillableConfig);

// Use it!
String result = jsonb.toJson(pojo);