Java JsonPath:将嵌套的 json 对象提取为字符串

Jon*_*ess 3 java json jsonpath

我需要获取一个 json 字符串,它是更大 json 的一部分。举个简单的例子,我只想提取file01,我需要json对象作为字符串。

{
    "file01": {
        "id": "0001"
    },
    "file02": {
        "id": "0002"
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,在代码中是这样的:

String file01 = JsonPath.parse(jsonFile).read("$.file01").toJson();
System.out.println(file01);  // {"id":"0001"}
Run Code Online (Sandbox Code Playgroud)

我想使用库JsonPath,但我不知道如何获得我需要的东西。

任何帮助表示赞赏。谢谢!

gly*_*ing 7

默认解析器 inJsonPath会将所有内容作为 a 读取,LinkedHashMap因此输出read()将是 a Map。您可以使用 Jackson 或 Gson 等库将其序列Map化为 JSON 字符串。但是,您也可以JsonPath在内部为您执行此操作。

为此,JsonPath您可以JsonPath使用 的不同实现进行配置,该实现AbstractJsonProvider允许您将解析结果作为 JSON 进行处理。在下面的示例中,我们使用GsonJsonProvider并且该read()方法的输出一个 JSON 字符串。

@Test
public void canParseToJson() {
    String json = "{\n" +
            "    \"file01\": {\n" +
            "        \"id\": \"0001\"\n" +
            "    },\n" +
            "    \"file02\": {\n" +
            "        \"id\": \"0002\"\n" +
            "    }\n" +
            "}";

    Configuration conf = Configuration.builder().jsonProvider(new GsonJsonProvider()).build();

    JsonObject file01 = JsonPath.using(conf).parse(json).read("$.file01");

    // prints out {"id":"0001"}
    System.out.println(file01);
}
Run Code Online (Sandbox Code Playgroud)