Reading and Writing Configuration Files with JSON-B

JSON-B ships with Java EE 8 and is already included in the API:

In standalone applications, like e.g. CLI, you will have to add the SPI (Service Provider Implementation) dependency:

Public POJO fields are serialized per default, private field serialization needs customization.

The following POJO:

import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.json.bind.JsonbConfig;

public class Configuration {

    public String workshop;
    public int attendees;

    private final static String CONFIGURATION_FILE = "airhacks-config.json";

    public Configuration save() {
        Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withFormatting(true));
        try (FileWriter writer = new FileWriter(CONFIGURATION_FILE)) {
            jsonb.toJson(this, writer);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        return this;


    public static Configuration load() {
        if (!Files.exists(Paths.get(CONFIGURATION_FILE))) {
            return new Configuration().save();
        try (FileReader reader = new FileReader(CONFIGURATION_FILE)) {
            return JsonbBuilder.create().fromJson(reader, Configuration.class);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
} directly written:

public void loadAndSave() {
    Configuration configuration = Configuration.load();
    configuration.attendees = 13;
    configuration.workshop = "Cloudy Jakarta EE";;


    "attendees": 13,
    "workshop": "Cloudy Jakarta EE"
JSON-B provides additional features like e.g. formatting, which are not available in JSON-P. uses the above approach (see to store the private and public keys, issuer, as well as the JWT location.

Also checkout: "Reading and Writing Configuration Files with JSON-P"

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:


Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments