adam bien's blog

Reading and Writing Configuration Files with JSON-P 📎

JSON-P 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.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>    
JsonReader reads the configuration from InputStream:

    public final static String CONFIGURATION_FILE = "duke-config.json";

    public static JsonObjectBuilder load() throws FileNotFoundException {
        try (JsonReader reader = Json.createReader(new FileInputStream(CONFIGURATION_FILE))) {
            return Json.createObjectBuilder(reader.readObject());
        }
    }    
and the JsonWrite serializes an in-memory instance into a stream:

    public static void write(JsonObject configuration) {
        try (JsonWriter writer = Json.createWriter(new FileOutputStream(CONFIGURATION_FILE))) {
            writer.writeObject(configuration);
        } catch (FileNotFoundException ex){}
    }    
An JsonObject is a typed Map<String, JsonValue>, the values can be directly access with a key:

public static String getValue(String key) {
    JsonObject configuration = null;
    try {
        configuration = load().build();
    } catch (FileNotFoundException ex) {    }
    return configuration.getString(key);
}
jwtenizr.sh uses the above approach (see Configuration.java to store the private and public keys, issuer, as well as the JWT location.

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.