6

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!

2
  • which library is this JsonPath ? Commented Aug 29, 2018 at 13:09
  • Jayway JsonPath from github.com/json-path/JsonPath Commented Aug 29, 2018 at 13:10

2 Answers 2

10

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.