如何检查 JSON 数组的所有元素是否都以特定字符串开头?

How to check whether all elements of a JSON array start with a specific string?

输入数据如下所示。

[
  { 
    "mahKey": "mahString.yolo",
    "mahValue": "0"
  },
  {
    "mahKey": "notMahString.crymeariver",
    "mahValue": "1"
  },
  {
    "mahKey": "mahSTring.omg",
    "mahValue": "2"
  }
]

所以我有这个。

resultActions
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(jsonPath("$.*", isA(ArrayList.class)))
        .andExpect(jsonPath("$.[mahKey]", Matchers.everyItem(Matchers.startsWith("mahString"))));

$.[mahKey]之后的数组如下所示。

[
  "mahString.yolo",
  "notMahString.crymeariver",
  "mahSTring.omg"
]

但是,我收到以下错误:

com.jayway.jsonpath.InvalidPathException: Could not parse token starting at position 3. Expected ?, ', 0-9, * 

如何在 JUnit 中检查 JSON 数组的所有元素是否都以特定字符串开头?

应该这样做:

"$.*.mahKey"

所以语法看起来像:

 .andExpect(MockMvcResultMatchers.status().isOk())
 .andExpect(jsonPath("$.*", isA(ArrayList.class)))
 .andExpect(jsonPath("$.*.mahKey", Matchers.everyItem(Matchers.startsWith("mahString"))));

Tested here,它正确检索了元素: