如何使用 JsonPath 从 json 中查找给定键的值?

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

我搜索了很多,但没有任何答案对我有帮助。

[{
    "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);

我试图获取密钥 d.read(key) 但它没有工作,因为它给出了一个值数组。

如何获取特定键的所有值的数组?有一件事要补充更多。我可以使用 d.read("$..created_date") 获取所有值的数组 但是我必须制作通用函数,所以我将键名作为参数,我必须找到给定键的所有值。

例如:created_date:[101, 102, 103..]

我也试过使用 Jackson。我不能使用除此之外的库。

我们将不胜感激。

希望这段代码能满足您的要求

代码:

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

    }

}