Search code examples
javajsonrestspring-bootproperty-files

Produce a JSON structure by reading a property file using SpringBoot


I'm writing a method in SpringBoot which reads the property file and produce JSON through endpoints. My property file looks like this:

Category.1=Quality=A,B,C,D
Category.2=Program=E,F,G
Category.3=Efficiency=H,I,J,K

I need to read only the values which is starting from Category ,my property file may contain other data. The JSON should look like this:

{
"Quality":[
  "A",
  "B",
  "C",
  "D"
],
"Program":[
  "E",
  "F",
  "G"
],
"Efficiency":[
  "H",
  "I",
  "J",
  "K"
]
}

I need to create a REST endpoints to get this JSON value. I know how to read the property file and get the values. As this property file is bit complex to me I need to get Quality , Program and efficiency as the key and remaining as it's value. I'm new to programming please help me out.


Solution

  • Use a library such as jackson to create the json. A working example with the properties you specified is here. A few basic steps:

    1. Get the properties
    2. Create an empty json object node
    3. Iterate over the properties, getting the ones you need (that have keys starting with "Category" in your case)
    4. Split each valid property value on the = to break it into the json key you want and the csv list of categories
    5. Create a json array out of each list in (4)
    6. Add this array to the node in (2) with the key in (4)

    Add the dependencies

    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.4'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.4'
    

    to your project for the example to work.

    public static void main(String... args) throws IOException {
        Properties p = new Properties();
        p.load(Test.class.getResourceAsStream("/myfile.properties"));
    
        ObjectNode node = JsonNodeFactory.instance.objectNode();
    
        String prefix = "Category.";
        String delimiter = ",";
    
        p.forEach((k, v) -> {
            String propKey = k.toString();
            if (propKey.startsWith(prefix)) {
                String[] propVal = v.toString().split("=");
                ArrayNode array = JsonNodeFactory.instance.arrayNode();
                for (String arrVal : propVal[1].split(delimiter)) {
                    array.add(arrVal);
                }
                node.set(propVal[0], array);
            }
        });
    
        System.out.println(node);
    }