我想在根级别测试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值,则路径存在