adam bien's blog

Reading and Writing Configuration Files with JSON-B 📎

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

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>    
In standalone applications, like e.g. CLI, you will have to add the SPI (Service Provider Implementation) dependency:

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0.3</version>
</dependency>        
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</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);
        }
    }
}    

...is directly written:

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

to:

{
    "attendees": 13,
    "workshop": "Cloudy Jakarta EE"
}    
JSON-B provides additional features like e.g. formatting, which are not available in JSON-P.

jwtenizr.sh uses the above approach (see Configuration.java 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: airhacks.io.