首页 > 解决方案 > JSON 路径没有值

问题描述

如何为以下结合了字符串和数组的 JSON 编写 mockMVC 测试。

{
  "id":1,
  "firstName":"NPA",
  "lastName":"TAS",
  "mobile":"123454321",
  "email":"ABCD@GMAIL.COM",
  "accounts":[
         {
          "id":1,
          "balance":"$1000",
          "custid":"1",
          "accNbr":"12345"
         }
            ]
}

我的代码:

@Test
        public void testJson() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
            mockMvc.perform(get("/acc/1")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.accounts.id", Matchers.is(1)))
            .andExpect(jsonPath("$.accounts.balance", Matchers.is("$1000")))
            .andExpect(jsonPath("$.accounts.accNbr", Matchers.is("12345")))
            .andExpect(jsonPath("$.accounts.custid", Matchers.is("1")))
            .andExpect(jsonPath("$.*", Matchers.hasSize(4)));
        }

我得到了例外

JSON 路径“$.accounts.id”没有值,异常:

预计在路径 $ 中找到具有属性 ['accounts'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是一个 json 对象。

但是,如果我尝试使用 $.accounts[0].id 我得到异常

JSON 路径“$.accounts[0].id”没有值,异常:

预计在路径 $ 中找到具有属性 ['accounts'] 的对象,但找到了 'net.minidev.json.JSONArray'。根据 JsonProvider:'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider',这不是一个 json 对象。

标签: unit-testingspring-mvcmockitojsonpathmockmvc

解决方案


accounts属性是一个数组,因此 this:$.accounts.id必须使用索引器,例如:$.accounts[0].id

文档

[<number> (, <number>)]     Array index or indexes

如果您不确定要使用哪个索引,则可以过滤 JSON 并在过滤后的帐户子文档上断言。例如:

  • $.accounts[?(@.id == 1)].balance: 返回$1000
  • $.accounts[?(@.accNbr == 12345)].id: 返回1
  • ... ETC

文档中有更多详细信息,您可以使用JsonPath 评估器来解决这个问题。


推荐阅读