在jsonpath中过滤时如何获取第一个元素?

Vu *_*ung 9 java jsonpath

所以我正在研究下面的json:

{
   "id": "",
   "owner": "some dude",
   "metaData": {
      "request": {
         "ref": null,
         "contacts":[
            {
               "email": null,
               "name": null,
               "contactType": "R"
            },
            {
               "email": null,
               "name": "Dante",
               "contactType": "S"
            }
         ]
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我想检索name联系人的类型S,只检索返回的第一个.

在此路径中使用jsonpath "$..contacts[?(@.contactType == 'S')].name"始终返回一个字符串数组,因为过滤器操作始终将结果作为数组返回.

所以,我想"$..contacts[?(@.contactType == 'S')].name[0]""$..contacts[?(@.contactType == 'S')][0].name",但没有运气.那些路径返回空结果.

所以我的问题是,在jsonpath中使用过滤器时,有没有办法获得第一个元素.我目前正在使用jayway jsonpath v2.2.0.

小智 1

如果您将 jsonpath 与 spring-test 中的 MockMvc 类一起使用,那么您可以编写以下虚拟匹配器:

import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.core.IsEqual;

import net.minidev.json.JSONArray;

public class FirstMatcher<T> extends BaseMatcher<T> {

    private final Matcher<?> matcher;

    public static <T> FirstMatcher<T> matcher(Matcher<T> matcher) {
        return new FirstMatcher<T>(matcher);
    }

    public static FirstMatcher<Object> value(Object value) {
        return new FirstMatcher<Object>(value);
    }

    public FirstMatcher(Matcher<T> matcher) {
        this.matcher = matcher;
    }

    public FirstMatcher(Object value) {
        this.matcher = new IsEqual<Object>(value); 
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("first matcher");
    }

    @Override
    public boolean matches(Object item) {
        if (!(item instanceof JSONArray)) {
            return false;
        }

        JSONArray array = (JSONArray)item;
        if (array.isEmpty()) {
            return false;
        }

        Object obj = array.get(0);
        return matcher.matches(obj);
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用以下方式:

mockMvc.
    perform(get(url).
            accept(MediaType.APPLICATION_JSON).accept(MediaType.TEXT_PLAIN).accept(MediaType.ALL)).
    andExpect(status().isOk()).
    andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)).
    andExpect(jsonPath("$.properties[?(@.propertyName == 'name1')].description").value(FirstMatcher.matcher(IsNull.nullValue()))).
    andExpect(jsonPath("$.properties[?(@.propertyName == 'name2')].required").value(FirstMatcher.value(true)));
Run Code Online (Sandbox Code Playgroud)

PS 由于 net.minidev.json.JSONArray 是 java.util.List 的子类,因此可以将其转换为 List 甚至 Iterable,而不是转换为 net.minidev.json.JSONArray。:)