我想在根级别测试JSON中是否存在某个键。
MvcResult result = mockMvc.perform(request)
.andExpect(status().isOk())
.andExpect(jsonPath("$.token").exists())
.andReturn();
我可以使用MockMVC类中的jsonPath进行测试。
但是如果我已经有一个json字符串,我该如何断言?
Assert(jsonString, hasKey??)
您可以像下面检查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值,则路径存在