Reputation: 2008
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!
Upvotes: 6
Views: 16913
Reputation: 11
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);}
Upvotes: 0
Reputation: 47865
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);
}
Upvotes: 10