开发者社区> 问答> 正文

JSONPath.extract同一个parser只有第一次成功

请问 不同的JSONPath使用extract方法 提取同一个解析器的内容 第二次extract会得到null值 是BUG嘛 还是设定只能解析一次

提问47.png

@Test public void jsonPathTest() { String seatString = "{\n" + "\t"flightId":"MH8633",\n" + "\t"column":"C",\n" + "\t"row":"19"\n" + "}"; JSONPath rowPath = JSONPath.of("$.row"); JSONPath colPath = JSONPath.of("$.column"); JSONReader parser = JSONReader.of(seatString); String row = (String)rowPath.extract(parser); String col = (String)colPath.extract(parser); System.out.println(row); System.out.println(col); }

原提问者GitHub用户MASON-PRINCE

展开
收起
大圣东游 2023-04-21 12:27:52 207 0
2 条回答
写回答
取消 提交回答
  • 值得去的地方都没有捷径

    不同的JSONPath使用extract方法提取同一个解析器的内容,第二次extract会得到null值,这是因为解析器在第一次extract之后已经被清空,无法再次提取内容。这是设定的限制,解析器只能解析一次。如果需要多次提取内容,可以在每次提取之前重新解析原始数据。

    2023-04-21 21:00:36
    赞同 展开评论 打赏
  • 要每次都new JSONReader,如下这样写:

    @Test
    public void jsonPathTest() {
        String seatString = "{\n" +
                "\t\"flightId\":\"MH8633\",\n" +
                "\t\"column\":\"C\",\n" +
                "\t\"row\":\"19\"\n" +
                "}";
        JSONPath rowPath = JSONPath.of("$.row");
        JSONPath colPath = JSONPath.of("$.column");
        String row = (String)rowPath.extract(JSONReader.of(seatString));
        assertEquals("19", row);
    
        String col = (String)colPath.extract(JSONReader.of(seatString));
        assertEquals("C", col);
    }
    

    你用这个快照版本,支持如下写法

    https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson/2.0.2-SNAPSHOT

    @Test
    public void test2() {
        String seatString = "{\n" +
                "\t\"flightId\":\"MH8633\",\n" +
                "\t\"column\":\"C\",\n" +
                "\t\"row\":\"19\"\n" +
                "}";
        JSONPath path = JSONPath.of("$['row','column']");
        Object result = path.extract(
                JSONReader.of(seatString));
        assertNotNull(result);
        assertEquals("[\"19\",\"C\"]", result.toString());
    }
    

    请使用更新版本:https://github.com/alibaba/fastjson2/releases/tag/2.0.2

    原回答者GitHub用户wenshao

    2023-04-21 15:08:11
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载