繁体   English   中英

JSON.parse()等效于mongo驱动程序3.x for Java

[英]JSON.parse() equivalent in mongo driver 3.x for Java

来自mongo的JSON.parse() (Java驱动程序)返回BasicDBList或BasicDBObject。

但是,在迁移到mongo驱动程序3.x时,返回DocumentList<Document>的新解析方法是什么?

在新的驱动程序中, Document.parse()仅解析对象,而不解析数组(在给定数组时抛出异常)。

对于具有3.x Java驱动程序的数组,JSON.parse()的等价物是什么?

解析任何JSON并获取DocumentList<Document>的简单技巧:

Document.parse("{\"json\":" + json + "}").get("json")

使用mongodb java驱动程序3.x解析JSON字符串数据:

解析JSON文档:

使用Document.parse()静态方法来解析单个JSON文档。

Document doc = Document.parse("{\"objA\":{\"foo\":1}}");

解析JSON数组:

使用BsonArrayCodec实例解码JsonReader

例如:

final String JSON_DATA
    = "[{\"objA\":{\"foo\":1}},"
    + "{\"objB\":{\"bar\":2}}]";

final CodecRegistry codecRegistry = CodecRegistries.fromProviders(asList(new ValueCodecProvider(),
    new BsonValueCodecProvider(),
    new DocumentCodecProvider()));

JsonReader reader = new JsonReader(JSON_DATA);
BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry);

BsonArray docArray = arrayReader.decode(reader, DecoderContext.builder().build());

for (BsonValue doc : docArray.getValues()) {
    System.out.println(doc);
}

参考: http//api.mongodb.org/java/3.2/org/bson/json/JsonReader.html,http : //api.mongodb.org/java/3.2/org/bson/codecs/BsonArrayCodec.html

这个怎么样:

Document doc = new Document("array", JSON.parse("[ 100, 500, 300, 200, 400 ]", new JSONCallback()));
System.out.println(doc.toJson()); //prints { "array" : [100, 500, 300, 200, 400] }

你是对的,没有简单的等价物。

如果使用行分隔的JSON文档而不是JSON数组,则它变得相当简单:

List<Document> getDocumentsFromLineDelimitedJson(final String lineDelimitedJson) {
    BufferedReader stringReader = new BufferedReader(
          new StringReader(lineDelimitedJson));
    List<Document> documents = new ArrayList<>();
    String json;
    try {
        while ((json = stringReader.readLine()) != null) {
            documents.add(Document.parse(json));
        }
    } catch (IOException e) {
        // ignore, can't happen with a StringReader
    }
    return documents;
}

例如,这个电话

System.out.println(getDocumentsFromLineDelimitedJson("{a : 1}\n{a : 2}\n{a : 3}"));

将打印:

[文件{{a = 1}},文件{{a = 2}},文件{{a = 3}}]

对我来说最简单的等价是使用任何json库将json转换为POJO。 以下是使用jackson的示例:

String input = "[{\"objA\":{\"foo\":1}},{\"objB\":{\"bar\":2}}]";
ObjectMapper mapper = new ObjectMapper();
List<Document> output = (List<Document>) mapper.readValue(input, List.class)
            .stream().map(listItem -> new Document((LinkedHashMap)listItem))
            .collect(Collectors.toList());

为完整性添加了对@Oleg Nitz答案的演员表。

Object object = Document.parse("{\"json\":" + jsonData.getJson() + "}").get("json");

if (object instanceof ArrayList) {
    documents = (ArrayList<Document>) object;
} else (object instanceof Document) {
    document = (Document) object;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM