java - 点的 JsonPath JUnit 转义字符

标签 java json spring spring-mvc junit

我有一个名为 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 的任何转义字符吗?

最佳答案

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

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

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

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

关于java - 点的 JsonPath JUnit 转义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19726859/

相关文章:

php - 为什么这个简单的 JSON 编码不起作用?

java - 用java将json序列化为rdf

java - 为什么我的 Spring Security 身份验证不起作用?

java - 无法在 Windows 7 下使用 ProcessBuilder 在 Java 中执行 javac 或其他命令行应用程序

c# - C# 中的 Google Geocoding Json 解析问题

java - 在 web.xml url-pattern 匹配器中是否有排除 URL 的方法?

java - 如何从其他应用程序检索 Spring-batch 作业历史记录?

java - if (string.contains) 在最终输出中混合变量放置

java - Android MediaRecorder NullPointerException

java - 项目中的代码打包后如何编写调用Jar文件的Maven脚本?