{ "Getting" : "started" }

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

Add Dependencies

Add the following repositories to your Maven project:

    <!-- Needed for JSON-B API -->
        <name>Maven Java Net Snapshots and Releases</name>

Add the following dependencies:



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<>();

// 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);