Search code examples
javajsonparsingjacksonjsonpath

How to find value of given key from json using JsonPath?


I have searched a lot but no answer helped what I want.

[{
    "activity_id": 1,
    "created_date": 104,
    "note_id": 1
}, {
    "activity_id": 2,
    "created_date": 101,
    "note_id": 2
}, {
    "activity_id": 3,
    "created_date": 105,
    "note_id": 3
}, {
    "activity_id": 4,
    "created_date": 102,
    "note_id": 4
}, {
    "activity_id": 5,
    "created_date": 103,
    "note_id": 5
}]

DocumentContext dc =  JsonPath.parse(data);

I have tried to get key d.read(key) but it didn't work as it gives an array of values.

How can I get an array of all values of a particular key? There is one thing to add more. I can get array of all values using d.read("$..created_date") But I have to make generic functions so I will take the key name as a parameter and I have to find all values of that given key.

For example: created_date: [101, 102, 103..]

I tried using Jackson also. I cannot use a library other than this.

Any help will be appreciated.


Solution

  • Hope this code works for your requirement

    Code:

    import java.util.List;
    
    import com.jayway.jsonpath.JsonPath;
    
    public class TestJsonPath {
    
        public static void main(String[] args) {
            String key = "created_date";
            testJsonPath(key);
        }
    
        private static void testJsonPath(String key) {
    
            String json = "{\"list\" : { \"time\": [{\"activity_id\":1,\"created_date\":104,\"note_id\":1},{\"activity_id\":2,\"created_date\":101,\"note_id\":2},{\"activity_id\":3,\"created_date\":105,\"note_id\":3},{\"activity_id\":4,\"created_date\":102,\"note_id\":4},{\"activity_id\":5,\"created_date\":103,\"note_id\":5}] } }";
            System.out.println(json);
            List<Object> createdDate = JsonPath.read(json, String.format("$.list.time[*].%s", key));
            System.out.println(createdDate);
    
        }
    
    }