首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java json-path库问题

Java json-path库问题
EN

Stack Overflow用户
提问于 2019-12-17 22:10:00
回答 1查看 406关注 0票数 0

全。我和https://github.com/json-path/JsonPath有一个非常奇怪的问题

其中一个问题似乎是实现所具有的可重入问题:当执行路径时,每个片段都返回一个字符串:

代码语言:javascript
复制
Expected to find an object with property ['ModuleListResponse'] in path $[0]['response'] but found 'java.lang.String'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.

我通过将JSON对象/JSON数组传递给JsonPath.read()而不是JSON字符串来实现了这一点。在这样做之后,现在我得到了:

代码语言:javascript
复制
Filter: [0]['name'] can only be applied to arrays. Current context is: [{"startLocation":{"types":["city"],"address":"Argentina","latitude":-34.6075682,"name":"Buenos Aires","description":"Buenos Aires is the capital and largest city of Argentina. The city is located on the western shore of the estuary of the Río de la Plata, o...449a049a781"}}]

如您所见,这已经是一个数组了。我已经用谷歌搜索了很多次,但找不到问题出在哪里。

关于解析它的代码,你已经知道了:

代码语言:javascript
复制
    jsonString = StringUtils.trim(jsonString);
    if (jsonString.startsWith("[")) {
        jsonObject = new org.json.JSONArray(jsonString);
    } else {
        jsonObject = new JSONObject(jsonString);
    }
    String jsonPath = "$[0].name";
    Object jsonResult = JsonPath.using(conf)
                             .parse(jsonObject)
                             .read(jsonPath);

因此,问题是:为什么JsonPath将json读取为字符串,而不是json?对于第二个问题,为什么它不将其作为数组,而它显然是一个数组。

EN

回答 1

Stack Overflow用户

发布于 2019-12-20 00:52:39

如果将JSON格式化为易于阅读的格式,您将看到属性路径是不正确的。下面是实际的JSON:

代码语言:javascript
复制
[
  {
  "startLocation": 
    {
      "types": ["city"],
      "address": "Argentina",
      "latitude": -34.6075682,
      "name": "Buenos Aires",
      "description": "Buenos Aires is the capital and largest city of Argentina. The city is located on the western shore of the estuary of the Río de la Plata, o...449a049a781"
    }
  }
]

您正在尝试访问$.[0].name,但该值不存在。

$.[0]

代码语言:javascript
复制
{
    "startLocation": {
      "types": ["city"],
      "address": "Argentina",
      "latitude": -34.6075682,
      "name": "Buenos Aires",
      "description": "Buenos Aires is the capital and largest city of Argentina. The city is located on the western shore of the estuary of the Río de la Plata, o...449a049a781"
}

$.[0]的惟一顶级密钥是startLocation,所以您实际要找的是

$.[0].startLocation.name

我建议撤销你添加的JSONArray和JSONObject毛发,因为它可能掩盖了真正的问题,那只是一个无效的属性路径。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59376047

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档