3

Is it possible to create a JSON configuration form a String in Apache commons configuration so that I can get some values from it?

For example, if I'd have a String containing this configuration, I'd like to be able to convert it into an org.apache.commons.configuration2.json.JSONConfiguration so that I can get values from it with the getX(nodeName) method (ex.: config.getInt("sectionA.valueB") would return 332):

{sectionA:{valueA:true, valueB:332}, sectionB:{valueA:124, valueB:"abc"}}

Would I have to wrap the string in something such as a Reader so that I can use the configuration's load(Reader) method? If yes, what would be the shortest and fastest way to do that?

2 Answers2

1

I'd much rather use JSON than XML, but short of writing my own JSON shim for the library, I don't see any 'built in' solution.

Evvo
  • 481
  • 5
  • 8
0

Instantiate a FileBasedConfigurationBuilder using the JSONConfiguration class (version >= 2.2):

Configurations configs = new Configurations();

FileBasedConfigurationBuilder<JSONConfiguration> builder =
    configs.fileBasedBuilder(JSONConfiguration.class, file);

Unfortunately, I have not found a way to get JSONConfiguration to pretty print. Overriding the class is not an option as it uses of private fields. It is simple, however, to supply your own class (copy JSONConfiguration) and modify the write method:

@Override
public void write(final Writer out) throws ConfigurationException, IOException {

    this.mapper.writerWithDefaultPrettyPrinter().writeValue(out,
        constructMap(this.getNodeModel().getNodeHandler().getRootNode()));

}
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](//creativecommons.org/licenses/by-sa/3.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221) – double-beep Apr 11 '19 at 13:38