What is JSON-B?
JSON-B is a standard binding layer for converting Java objects to/from JSON messages. It defines a default mapping algorithm for converting existing Java classes to JSON, while enabling developers to customize the mapping process through the use of Java annotations.
Consistent
Consistent with JAXB (Java API for XML Binding) and other Java EE and SE APIs where appropriate
Conventional
Define default mapping of Java classes and instances to JSON document counterparts
Customizable
Allow customization of the default mapping definition
Easy to Use
Default use of the APIs should not require prior knowledge of the JSON document format and specification
To serialize/deserialize a Java Object to/from JSON
The Java Class
public class Dog {
public String name;
public int age;
public boolean bitable;
}
JSON-B API calls
public static void main(String[] args) {
// Create a dog instance
Dog dog = new Main.Dog();
dog.name = "Falco";
dog.age = 4;
dog.bitable = false;
// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);
System.out.println(result);
// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bitable\":false}", Dog.class);
}
The JSON representation
{
"name": "Falco",
"age": 4,
"bitable": false
}