jsonpath:JSON路径:$ .id无值,例外:路径'id'正在应用于数组。数组不能具有属性

emo*_*ssi 4 java spring json mocking mockmvc

我试图用jsonPath读取json的内容,但出现错误。

这里是junit的测试方法:

mockMvc.perform(get("/path")
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", is(1)))
                .andExpect(jsonPath("$.name", is("NAME")))
                .andReturn().getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)

这是请求返回我的内容:

[{"id":1,"name":"NAME","....}, ....}]
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

No value for JSON path: $.id, exception: Path 'id' is being applied to an array. Arrays can not have attributes.
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗。

谢谢

wer*_*ero 5

响应返回一个JSON数组,并使用"$.id"您尝试访问该id数组的属性。如错误消息所示,这是不可能的。

在数组的第一个元素上测试idand name属性:

.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("NAME")))
Run Code Online (Sandbox Code Playgroud)