Configuring the Jsonb instance

From the previous posts we can see that an instance of Jsonb is used for serialization/deserialization of java objects to/from json format.

We can configure the Jsonb instance by creating an instance of JsonbConfig.

By default jsonb implementation provider must support the following properties to be configured. – java.lang.Boolean
Controls whether or not the Jsonb toJson() methods will format the resulting JSON data with line breaks and indentation. A true value for this property indicates human readable
indented data, while a false value indicates unformatted data. Default value is false (unformatted) if this property is not specified. – java.lang.String
The Jsonb serialization toJson() methods will default to this property for encoding of output JSON data. Default value is ‘UTF-8’ if this property is not specified.

jsonb.from.json.encoding – java.lang.String
The Jsonb deserialization fromJson() methods will default to this property encoding of input JSON data if the encoding cannot be detected

Below example shows how to configure and create Jsonb instance

Main Code

1 import javax.json.bind.Jsonb;
2 import javax.json.bind.JsonbBuilder;
3 import javax.json.bind.JsonbConfig;
5 public class JsonbDemo5 {
6 public static void main(String[] args) {
7 JsonbConfig jsonbConfig = new JsonbConfig();
8 jsonbConfig.setProperty(JsonbConfig.FORMATTING, true);
10 Jsonb jsonb = JsonbBuilder.create(jsonbConfig);
12 Person person = new Person();
13 person.setfName(“fName”);
14 person.setlName(“lName”);
15 person.setAge(10);
17 String result = jsonb.toJson(person);
18 System.out.println(result);
19 }


At line 7 we create an instance of JsonbConfig and at line 8, we enable json formatting by setting the property “JsonbConfig.FORMATTING” to true.

We pass the JsonbConfig instance as an argument to JsonbBuilder’s create method. JsonbBuilder use the information provided by the JsonbConfig instance and create
the Jsonb instance.

In this case, a Jsonb instance will be created which will format the json string obtained after serialization of java object.


“age”: 10,
“fName”: “fName”,
“lName”: “lName”

Leave a Reply