I have a below JSON and from which I need to make a Map
. In the below JSON, I have only three levels of parentCategory
but in
Generally speaking - The best tool for the task of retrieving particular JSON properties is Json-Path which provides a rich query language to search a JSON tree.
Regarding the question, it is requried to retrieve two unrelated properties, so two scans of the JSON tree are required. The question does not specify how the input is read, so perhaps it is possible to read the whole input stream into one String.
Below is the code with the queries needed to retrieve both properties. This will work regardless of the number of parentCategory
levels. The trick is that the last object is the only one that does not have a child parentCategory
.
I have added comments to the code that explain the query text
String categoryIdJsonPath =
"$" + // start from tree root
".listings[0]" + // get listings array's first (only) object
".categories[0]" + // get categories array's first (only) object
".id"; // get id property
String lastParentIdJsonPath =
"$" + // start from tree root
".listings[0]" + // get listings array's first (only) object
".categories[0]" + // get categories array's first (only) object
"..parentCategory" + // do deep scan for all nested parentCategory objects
"[?(!(@.parentCategory))]" + // filter by the object that does NOT have parentCategory property
".id"; // get id property
try {
// read the whole input so it can be scanned twice
String jsonInput = new String(Files.readAllBytes(Paths.get("C://temp/test.json")), Charset.forName("UTF-8"));
String categoryId = JsonPath.read(jsonInput, categoryIdJsonPath);
System.out.println(categoryId);
// return type is always List when deep scan is requested
List<String> lastParent = JsonPath.read(jsonInput, lastParentIdJsonPath);
System.out.println(lastParent.get(0));
} catch (Exception e) {
e.printStackTrace();
}