JsonPath JUnit用于点的转义字符

clo*_*her 12 java junit spring json spring-mvc

我有一个名为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));
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下异常,因为这些点被解释为路径:

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 
Run Code Online (Sandbox Code Playgroud)

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

Ida*_*Ida 40

在您的字段周围使用括号和引号.例如,如果您的字段是valid.key.with.dot

请参考它['valid.key.with.dot']并在JsonPath中尝试

JsonPath.read(jsonString, "$.['valid.key.with.dot']")
Run Code Online (Sandbox Code Playgroud)

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


Rom*_*val 18

正如艾达所 指出的那样:

在您的字段周围使用括号和引号.例如,如果您的字段是valid.key.with.dot

请将其称为['valid.key.with.dot']并在JsonPath中尝试

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


Mic*_*ess 5

这些天(例如io.rest-assured.json-path:3.0.1)符号似乎没有括号:

// Some Groovy OData V4 $count test
// Response looks like:
// { "@odata.count": 2, ... }
body "'@odata.count'", equalTo(2)
Run Code Online (Sandbox Code Playgroud)

在这个 Git 问题中找到了相应的提示。