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

6

我需要获取一个较大的json字符串中的一部分json。以简化示例为例,我只想提取文件01,并且我需要将该json对象作为字符串获取。

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

因此,在代码中应该像这样:

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

我想使用JsonPath库,但是我不知道如何获取我需要的内容。

非常感谢您的帮助。


这个 JsonPath 是哪个库? - pvpkiran
Jayway JsonPath 来自 https://github.com/json-path/JsonPath - Jonas_Hess
2个回答

10
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);
}

0

这是可行的解决方案!

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);}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接