将List <document>解析为java

时间:2018-07-12 02:46:50

标签: java list document

我有一个文档

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

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

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

*注意:我使用的是java8,org.bson.Document

1 个答案:

答案 0 :(得分:2)

创建class以在列表data中保留一个对象:

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

使用Jackson映射器将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);