JSONPath和Traverson过滤:单个元素数组

时间:2019-08-02 11:56:08

标签: java json jsonpath

这是我要与Traverson处理的Json,以从此HAL中提取单个链接:

{
  "_links": {
    "curies": [
      {
        "href": "https://localhost/auth/def/rels/{rel}",
        "name": "auth",
        "templated": true
      }
    ],
    "self": {
      "href": "https://localhost/auth/identity"
    }
  },
  "_embedded": {
    "auth": [
      {
        "_links": {
          "auth:ad": [
            {
              "href": "https://localhost/auth/ad"
            }
          ]
        },
        "kind": "oauth2"
      },
      {
        "_links": {
          "auth:default": [
            {
              "href": "https://localhost/auth/default" // **Link that I need**
            }
          ]
        },
        "kind": "oauth2"
      }
    ]
  }
}

理想情况下,负责处理的Java代码应如下所示:

Link test = traverson
        .follow("auth")
        .follow("$.['_embedded']['auth']..['_links']['auth:default']..['href'][0]")
        .asLink();

但是由于某种原因,尽管在JSONPath表达式中添加最后一个[0]之前,我得到的是一个元素的数组,但我却没有获得成功。有没有一种方法可以提取此单个链接,以使我不返回数组?我用这个tool进行测试。

1 个答案:

答案 0 :(得分:0)

实现我应如下所示所需的代码:

JsonPathLinkDiscoverer disc = new JsonPathLinkDiscoverer("$._embedded..auth.._links..['%s']..href", MediaTypes.HAL_JSON);
Link authLink = disc.findLinksWithRel("auth:default", <json>).get(0);

其中<json>应该是原始问题中示例的json表示形式(可能类似于其他调用的响应)。