一般而言-检索特定JSON属性的最佳工具是Json-Path,它提供了丰富的查询语言来搜索JSON树。
关于该问题,需要检索两个不相关的属性,因此需要对JSON树进行两次扫描。该问题未指定如何读取输入,因此也许可以将整个输入流读取为一个String。
下面是带有检索这两个属性所需的查询的代码。无论
parentCategory级别数如何,这都将起作用。诀窍在于,最后一个对象是唯一没有孩子的对象
parentCategory。
我已经在解释查询文本的代码中添加了注释
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(); }


