4

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

这里的junit测试方法:

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

这是请求返回给我的内容:

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

我收到了这个错误:

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

有人可以帮助我。

谢谢

4

1 回答 1

5

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

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

.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("NAME")))
于 2016-02-07T09:51:02.837 回答