mayooran mayooran - 13 days ago 4
Java Question

Best way to find the pre-defined schema properties in a json file

I have a json schema file which follows the custom rules I've created. This schema file is a valid json file. It follows the below pattern.

{
"name": {
"fname" : {
"displayName":"FirstName",
"dataType":"String"
}
"lname" : {
"displayName":"LastName",
"dataType":"String"
}
},
"address": {
"displayName":"Address",
"dataType":"String"
}
}


so based on the schema I need to create the below json with respective values.

{
"name": {
"FirstName": "test",
"LastName" : "test1"
},
"Address" : "someAddress"
}


So when I get the schema, what is the best way to find the config information node? That is the leaf node which has the displayName and dataType parameters. Currently I'm traversing this tree using Jackson json and finding the nodes with displayName and dataType keys. Because I cannot precisely say at which level this leaf node could be present. Is there a better way to handle this situation than traversing the whole json tree looking for the elements?

Answer

I was not sure wnat exactly is required (do you want the fname object or the value of its properties), however, JsonPath seems like a good fit here. It is the equivalent of xpath for json - search hierarchy model based on various criteria

I made a small demo to get you started. you just need to twaek the query string to suit your requirements. You can use the Jayway JsonPath Evaluator as REPL

import java.nio.file.*;
import com.jayway.jsonpath.*;
public class JsonPathDemo
{
    public static void main(String[] args)
    {
        // query: get all json objects that have displayName and dataType properties
        String jsonPathQuery = "$..*[?(@.displayName && @.dataType)]";
        try {
            String content = new String(Files.readAllBytes(Paths.get("C://temp/xx.json")));
            Object parsedContent = Configuration.defaultConfiguration().jsonProvider().parse(content);
            Object configElements = JsonPath.read(parsedContent, jsonPathQuery);
            System.out.println(configElements.getClass());
            System.out.println(configElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

output is

class net.minidev.json.JSONArray
[{"displayName":"Address","dataType":"String"},{"displayName":"FirstName","dataType":"String"},{"displayName":"LastName","dataType":"String"}]
Comments