Human editable JSON-like or YAML-like program configuration in Java

9.9k views Asked by At

Is there a Java library similar to libconfig for C++, where the config file is stored in a JSON-like format that can be edited by humans, and later read from the program?

I don't want to use Spring or any of the larger frameworks. What I'm looking for is a small, fast, self-contained library. I looked at java.util.Properties, but it doesn't seem to support hierarchical/nested config data.

4

There are 4 answers

0
mguymon On BEST ANSWER

I think https://github.com/typesafehub/config is exactly what you are looking for. The format is called HOCON for Human-Optimized Config Object Notation and it a super-set of JSON.

Examples of HOCON:

HOCON that is also valid JSON:

{
    "foo" : {
        "bar" : 10,
        "baz" : 12
    }
}

HOCON also supports standard properties format, so the following is valid as well:

foo.bar=10
foo.baz=12

One of the features I find very useful is inheritance, this allows you to layer configurations. For instance a library would have a reference.conf, and the application using the library would have an application.conf. The settings in the application.conf will override the defaults in reference.conf.

Standard Behavior for loading configs:

The convenience method ConfigFactory.load() loads the following (first-listed are higher priority):

  • system properties application.conf (all resources on classpath with this name)
  • application.json (all resources on classpath with this name)
  • application.properties (all resources on classpath with this name)
  • reference.conf (all resources on classpath with this name)
2
maksimov On

There's a Java library to handle JSON files if that's what you're looking for:

http://www.json.org/java/index.html

Check out other tools on the main page:

http://json.org/

0
esaj On

Apache Commons Configuration API and Constretto seem to be somewhat popular and support multiple formats (no JSON mentioned, though). I've personally never tried either, so YMMV.

0
tokhi On

I found this HOCON example:

my.organization {
    project {
        name = "DeathStar"
        description = ${my.organization.project.name} "is a tool to take control over whole world. By world I mean couch, computer and fridge ;)"
    }
    team {
        members = [
            "Aneta"
            "Kamil"
            "Lukasz"
            "Marcin"
        ]
    }
}
my.organization.team.avgAge = 26

to read values:

val config = ConfigFactory.load()
config.getString("my.organization.project.name")  // => DeathStar
config.getString("my.organization.project.description") // => DeathStar is a tool to take control over whole world. By world I mean couch, computer and fridge ;)
config.getInt("my.organization.team.avgAge") // => 26
config.getStringList("my.organization.team.members") // => [Aneta, Kamil, Lukasz, Marcin]

Reference: marcinkubala.wordpress.com