Reputation: 4207
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?
Upvotes: 1
Views: 796
Reputation: 14328
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"}]
EDIT: answer for question in comment:
It is possible to check for path existence (and make all sorts of other assertions) using json-path-assert:
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;
// query for specific path
String jsonSpecificPathQuery = "$..name.fname.displayName";
String content = new String(Files.readAllBytes(Paths.get("C://temp/xx.json")));
Object parsedContent = Configuration.defaultConfiguration().jsonProvider().parse(content);
System.out.println("hasJsonPath? " + hasJsonPath(jsonSpecificPathQuery).matches(parsedContent));
Upvotes: 1