小编Ros*_*tov的帖子

如何在 Java 中使用 JSONPath 搜索数组?

我想使用 json-path-assert 为 Web 服务编写单元测试。鉴于此 JSON:

[ 
  ["Some short name","Some parent","Some name"],
  ["Some short name 2","Some parent 2","Some name 2"] 
]
Run Code Online (Sandbox Code Playgroud)

我想检查“Some name 2”的父级是否为“Some parent 2”。我无法更改 JSON 的结构,因为它是由第三方库指定的。

这是我想出的 JSONPath 表达式:

$..[?(@[2] == 'Some name 2')][1]
Run Code Online (Sandbox Code Playgroud)

此表达式工作正常,并在此 JSON 工具中返回预期结果 ('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, …
Run Code Online (Sandbox Code Playgroud)

json jsonpath

1
推荐指数
1
解决办法
2万
查看次数

标签 统计

json ×1

jsonpath ×1