我搜索了很多,但没有答案能帮助我得到想要的。
[{
"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);
我尝试获取 key d.read(key)
但它不起作用,因为它给出了一个值数组。
如何获取特定键的所有值的数组?还有一件事需要补充一下。我可以使用 d.read("$..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);
}
}
关于java - 如何使用 JsonPath 从 json 中查找给定键的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61245014/