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

Java JsonPath: Extract nested json object as string

我需要一个 json 字符串,它是更大的 json 的一部分。 作为一个简化的示例,我只想提取 file01,并且我需要 json 对象作为字符串。

{
    "file01": {
        "id": "0001"
    },
    "file02": {
        "id": "0002"
    }
}

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

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

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

感谢任何帮助。 谢谢!

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

要在 JsonPath 中执行此操作,您可以使用 AbstractJsonProvider 的不同实现配置 JsonPath,这样您就可以将解析结果作为 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);
}

这是有效的解决方案!

public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("yourjson.json"));

Object res = JsonPath.read(obj, "$"); //your json path extract expression by denoting $

System.out.println(res);}