简体   繁体   中英

Java JsonPath: Extract nested json object as string

I need to get a json string, that is part of a larger json. As a simplified example, I want to extract only file01, and I need the json object as a string.

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

So, in code something like:

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

I would like to use the library JsonPath , but I do not know how to get what I need.

Any help is appreciated. Thanks!

The default parser in JsonPath will read everything as a LinkedHashMap so the output of read() will be a Map . You could use a library such as Jackson or Gson to serialise this Map into a JSON string. However, you can also get JsonPath to do this for you internally.

To do this within JsonPath you configure JsonPath with a different implementation of AbstractJsonProvider , one which allows you to get your hands on the parsed result as JSON. In the following example, we're using GsonJsonProvider and the output of the read() method is a JSON string.

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

Here is the solution that works!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM