首页 > 解决方案 > How to check whether all elements of a JSON array start with a specific string?

问题描述

The input data looks as follows.

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

So I have this.

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

The array after $.[mahKey] looks like this.

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

However, I get the following error:

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

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

标签: javajsonjunit

解决方案


This should do it:

"$.*.mahKey"

So the syntax would look like:

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

Tested here, it retrieved the elements correctly:

enter image description here


推荐阅读