编程语言
首页 > 编程语言> > java-jsonpath:JSON路径:$.id无值,例外:路径“ id”被应用于数组.数组不能具有属性

java-jsonpath:JSON路径:$.id无值,例外:路径“ id”被应用于数组.数组不能具有属性

作者:互联网

我试图用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.

有人可以帮我吗.

谢谢

解决方法:

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

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

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

标签:mockmvc,mocking,spring,json,java
来源: https://codeday.me/bug/20191027/1943996.html