我试图不是通过数组位置而是通过内容键来获取特定的数组项。
示例JSON:
{"items": [{
"key": "prop-name",
"label": "Provider",
"type": "DROPDOWN",
"items": ["bla", "blub", "what", "ever"]
}, {
"key": "prop-modes",
"label": "Transport modes",
"type": "CHECKBOX",
"items": ["AIR", "RAIL", "ROAD", "SEA"]
}
]}
private static String URL_GLOBAL_FILTER = "/global-filter";
private static String PROP_NAME = "prop-name";
mvc.perform(get(URL_GLOBAL_FILTER).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.items", hasSize(10)))
.andExpect(jsonPath("$.items[?((@.key === \"" + PROP_NAME + "\" && @.type === \"DROPDOWN\"))]").exists())
.andExpect(jsonPath("$.items[0].items", hasSize(4)));
这很好用。但是我想做的是这样的:
.andExpect(jsonPath("$.items[?(@.key == \"prop-name\")].items", containsString("bla")))
但这会引发以下错误:
java.lang.AssertionError: JSON path "$.items[?(@.key == "prop-name")].items"
预期:包含“ bla”的字符串 但是:是一个net.minidev.json.JSONArray(<[[“” bla“,” blub“,” what“,” ever“]]>)
< >
是什么意思?如何访问内部的数组?
在jsonQueryTool中,这似乎是我想要的。
(已更新的问题)
答案 0 :(得分:2)
您是否尝试过使用Hamcrest的hasItem
匹配器?
import static org.hamcrest.Matchers.*;
.andExpect(jsonPath("$.items[?(@.key == 'prop-name')].items[*]", hasItem("bla")));