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.
Use a library such as jackson to create the json. A working example with the properties you specified is here. A few basic steps:
=
to break it into the json key you want and the csv list of categoriesAdd 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);
}