繁体   English   中英

Java json-path 库的问题

[英]Issue with Java json-path library

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

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

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'.

我通过将 JSONObject/JSONArray 传递给 JsonPath.read() 而不是 JSON 字符串来“破解”它。 这样做之后,现在我得到:

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"}}]

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

关于解析它的代码,你有它:

    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? 对于第二个问题,当它显然是一个数组时,为什么不将其作为数组。

如果您将 JSON 格式化为易于阅读的格式,您会发现您的属性路径不正确。 这是实际的 JSON:

[
  {
  "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]

{
    "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 绒毛,因为它可能掩盖了真正的问题,这只是一个无效的属性路径。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM