将列表 <Document> 解析为 java 中的列表

Parse List<Document> to Lists in java

我有一个 文档 作为:

{
    "data" : [
        {
            "key1" : "value1",
            "key2" : "value2"
        },
        {
            "key1" : "value3",
            "key2" : "value4"
        }
    ]
}

将上面的 Document 解析为 2 个字符串列表的最佳方法是什么:

List<String> data.key1;
List<String> data.key2;

*注:我用的是java8、org.bson.Document

创建 class 以在列表 data 中保存单个对象:

class Data {
 private String key1;
 private String key2;
}

使用 Jackson Mapper 将 JSON 解析为您的对象并获取字段列表:

ObjectMapper mapper = new ObjectMapper();
List<Data> data = mapper.readValue(jsonString, List.class);

List<String> key1s = data.stream().map(d -> d.getKey1()).collect(Collectors.toList());

List<String> key2s = data.stream().map(d -> d.getKey2()).collect(Collectors.toList());

更新:如果你有jsonpath,那么查询起来更方便:

List<String> key1s = JsonPath.read("$.data[*].key1", jsonString);
List<String> key2s = JsonPath.read("$.data[*].key2", jsonString);