JsonPath JUnit 转义字符用于点

2022-09-01 21:32:16

我有一个名为 template.welcome.email 的json字段,我正在编写一个单元测试,用于检查该字段是否存在于服务器的回复中,但我找不到字段名称中点的转义。我的测试代码是:

@Test
public void testEmailTemplates() throws Exception {     
    mockMvc.perform(get("/emailTemplates")
        .contentType(MediaType.APPLICATION_JSON)
        .locale(Locale.UK)
        .accept(MediaType.APPLICATION_JSON))

        .andDo(print())
        .andExpect(status().isOk())

        .andExpect(jsonPath("$.template.welcome.email").exists())

        .andExpect(redirectedUrl(null))
        .andExpect(forwardedUrl(null));
}

但是我得到以下例外,因为点被解释为路径:

java.lang.AssertionError: No value for JSON path: $.template.welcome.email, exception: invalid path
at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:74)
at org.springframework.test.util.JsonPathExpectationsHelper.exists(JsonPathExpectationsHelper.java:121)
at org.springframework.test.web.servlet.result.JsonPathResultMatchers$3.match(JsonPathResultMatchers.java:77)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141)
at 

您知道 jsonPath 的任何转义字符吗?


答案 1

在字段两边使用方括号和引号。例如,如果您的字段有效.key.with.dot

在 JsonPath 中将其引用为和,请尝试['valid.key.with.dot']

JsonPath.read(jsonString, "$.['valid.key.with.dot']")

另请参阅此主题:https://groups.google.com/forum/#!topic/jsonpath/7YvgXWP1_7Y


答案 2

正如艾达所指出的

在字段两边使用方括号和引号。例如,如果您的字段有效.key.with.dot

将其引用为 ['valid.key.with.dot'],在 JsonPath 中,尝试

JsonPath.read(jsonString, "$.['valid.key.with.dot']")