如何声明JSON密钥,但不关心Java中的值?

问题描述 投票:0回答:1

我想在根级别测试JSON中是否存在某个键。

 MvcResult result = mockMvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.token").exists())
                .andReturn();

我可以使用MockMVC类中的jsonPath进行测试。

但是如果我已经有一个json字符串,我该如何断言?

Assert(jsonString, hasKey??)
json spring-boot junit assert
1个回答
0
投票

您可以像下面检查json的路径

String tree =
        "{\n"
            + "  \"tes\": {\n"
            + "    \"test1\":\"test12111\"\n"
            + "  }\n"
            + "}";

   ObjectMapper mapper = new ObjectMapper();
  JsonNode jsonNode = mapper.readTree(json);
  String value = jsonNode.path("tes").path("test1").textValue();

如果值是null,则路径不存在,如果获得非null值,则路径存在

© www.soinside.com 2019 - 2024. All rights reserved.