Configuring Object Instances from JSON in conf Files

124 views Asked by At

So I want to be able to basically make instances of a class from JSON definitions in a conf file. In looking through the docs, I found that there are ways to reference things that are defined in JSON structures, but I was wondering about how best to instantiate objects from such definitions. For instance, suppose I had a class called RemoteRepository with 4 or 5 properties. I'd like to make a bunch of entries in a JSON file then read in at startup and get back a collection of RemoteRepository objects. I could do this with a database, of course, including a graph one, but would like to just do JSON if possible.

2

There are 2 answers

0
Rob On BEST ANSWER

So I can make instances, but as usual, once I need a bunch of instances, it's time for a database. In this case, I ended up doing some simple XML files to trigger these instances. As much of a mess as XML is, for things like this, it does work best. Namely:

  • Some nesting of instance information
  • Not an exact mapping to the target class, e.g. field mappings are part of my config. I am going to load a few fields from the config file, but then create instances of a different class, hence the immediate conversion to a java class I would get from JSON is not meaningful

One other thing I figured out in doing this is that processing XML in Java is still kind of a mess. Still, this was the right way to go in this case.

2
ChrisS On

Assuming a static class definition that represents the JSON structure is acceptable, you can try the JSON C# Class Generator

Once you've generated your classes you can simply create a new instance or array of instances by passing in the json to the constructor that this tool creates on the generated class(es).