栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用杰克逊解析递归嵌套字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用杰克逊解析递归嵌套字段

一般而言-检索特定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();    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609238.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号