JSon for configuration: Apache Johnzon made another step with comments


Using JSon for a configuration file is very tempting but there is a big drawback: you can’t comment anything with a strict JSon parser.

This is something which is blocking for a configuration IMO because you often need to explain why you configured something in the way it is.

For that reason Johnzon now support a new property to be able to handle // and /**/ style comments.

This means such a json can now be read:

{
    // out apache proxy set it automatically
    "security": "BASIC",
    /*
     * you can find this configuration
     * in /etc/foo/bar/proxy.conf
     */
    "port": "9085"
}

However this is not activated by default (to ensure no overhead for all other cases like JAX-RS).

To activate comment handling you need to add to the reader/parser factory the property “org.apache.johnzon.supports-comments” to true (as boolean or string):

Map<String, Object> config = new HashMap<String, Object>();
config.put("org.apache.johnzon.supports-comments", true);
final JsonReader reader = Json.createReaderFactory(config).createReader(stream);
// ....
reader.close();

Of course this property has been propagated to Johnzon Mapper so you can now do:

final MyConfig config = new MapperBuilder()
                 .setSupportsComments(true)
                 .build()
                 .readObject(stream, MyConfig.class);

This really allows to use JSon for configuration which is quite nice cause the format is hierarchical and light in syntax!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s