Reputation:
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?
Upvotes: 3
Views: 4188
Reputation: 1
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()));
}
Upvotes: 0
Reputation: 499
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.
Upvotes: 1