【发布时间】:2016-03-30 20:23:09
【问题描述】:
我想使用 json-path-assert 为 Web 服务编写单元测试。鉴于此 JSON:
[
["Some short name","Some parent","Some name"],
["Some short name 2","Some parent 2","Some name 2"]
]
我想检查“Some name 2”的父级是否为“Some parent 2”。我无法更改 JSON 的结构,因为它是由第三方库指定的。
这是我想出的 JSONPath 表达式:
$..[?(@[2] == 'Some name 2')][1]
此表达式工作正常,并在this JSON tool 中返回预期结果('Some parent 2')。但是,当使用 JSONPath 库在 Java 中使用它时,我得到一个空结果而不是正确的值:
import com.jayway.jsonpath.JsonPath;
import org.junit.Test;
public class TestJSONPath
{
@Test
public void testJsonPath() {
String json = "[[\"Some short name\",\"Some parent\",\"Some name\"]," +
"[\"Some short name 2\",\"Some parent 2\",\"Some name 2\"]]";
System.out.println(JsonPath.read(json, "$[1][1]")); // OK, returns 'Some parent 2'
System.out.println(JsonPath.read(json, "$..[?(@[2] == 'Some name 2')][1]")); // Not OK, returns an empty list
}
}
这是我的 pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>2.1.0</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
您能帮我解决这个问题吗?
【问题讨论】: