jsonpath:JSON 路径没有值:$.id,异常:路径 'id' 正在应用于数组。数组不能有属性

jsonpath: No value for JSON path: $.id, exception: Path 'id' is being applied to an array. Arrays can not have attributes

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

这里是junit测试方法:

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

这是要求return我:

[{"id":1,"name":"NAME","....}, ....}]

我收到这个错误:

No value for JSON path: $.id, exception: Path 'id' is being applied to an array. Arrays can not have attributes.

谁能帮帮我。

谢谢

响应 returns 一个 JSON 数组并使用 "$.id" 您尝试访问该数组的 id 属性。正如错误消息告诉您的那样,这是不可能的。

改为在数组的第一个元素上测试 idname 属性:

.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("NAME")))