【问题标题】:jsonpath read does not work with json in String representationjsonpath read 不适用于字符串表示中的 json
【发布时间】:2015-02-24 20:16:50
【问题描述】:

我有一个以字符串格式表示的 JSON,如下所示,我正在使用 jsonpath.read 方法来查找我正在寻找的模式。

    String jsonExpr="{\"store\":"
             +"{"
               +"\"book\":"
                 +"   [ "
                   +"     { \"category\": \"reference\","
                     +"     \"author\": \"Nigel Rees\","
                       +"   \"title\": \"Sayings of the Century\","
                         +" \"price\": 8.95"
                        +"},"
                        +"{ \"category\": \"fiction\","
                         +" \"author\": \"Evelyn Waugh\","
                          +"\"title\": \"Sword of Honour\","
                          +"\"price\": 12.99"
                        +"},"
                        +"{ \"category\": \"fiction\","
                         +" \"author\": \"Herman Melville\","
                          +"\"title\": \"Moby Dick\","
                          +"\"isbn\": \"0-553-21311-3\","
                          +"\"price\": 8.99"
                        +"},"
                        +"{ \"category\": \"fiction\","
                          +"\"author\": \"J. R. R. Tolkien\","
                          +"\"title\": \"The Lord of the Rings\","
                          +"\"isbn\": \"0-395-19395-8\","
                          +"\"price\": 22.99"
                        +"}"
                    +"],"
                    +"\"bicycle\":"
                    +"{"
                       +" \"color\": \"red\","
                        +"\"price\": 19.95,"
                    +"}"
                +"}"
            +"}";

这是我试图找到 json 的模式。

        String matchString="$.store";

            String matchValue = JsonPath.read("'"+jsonExpr+"'",matchString).toString();
                            System.out.println(" Printing matched value "+matchValue);

但是我收到异常,指出在路径中找不到该属性,并且只有 $ 模式可以打印整个 JSON。通过 maven 使用 build 1.2.0。

Exception in thread "main" com.jayway.jsonpath.PathNotFoundException: Property ['store'] not found in path $
at com.jayway.jsonpath.internal.token.PropertyPathToken.evaluate(PropertyPathToken.java:41)
at com.jayway.jsonpath.internal.token.RootPathToken.evaluate(RootPathToken.java:53)
at com.jayway.jsonpath.internal.CompiledPath.evaluate(CompiledPath.java:53)
at com.jayway.jsonpath.internal.CompiledPath.evaluate(CompiledPath.java:61)
at com.jayway.jsonpath.JsonPath.read(JsonPath.java:179)

【问题讨论】:

  • 我也遇到了同样的问题。我将 json 放入文件中,并读取文本文件,然后使用 read() 方法并且有效:)。我知道我来晚了,很抱歉。

标签: json maven jsonpath


【解决方案1】:

试试这个:

Map<String, Object> result = JsonPath.read(jsonExpr, "$.store");

或者查看文档here。

【讨论】:

    猜你喜欢
    • 2017-10-07
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多