Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

JSON.parse() from mongo (Java driver) returns either a BasicDBList or a BasicDBObject.

However, when migrating to mongo driver 3.x, what's the new parse method that returns either Document or List<Document>?

In the new driver, Document.parse() only parses an object, not an array (throws an exception when given an array).

What is the equivalent of JSON.parse() for Arrays with 3.x Java drivers ?

like image 902
judepereira Avatar asked Dec 23 '15 13:12

judepereira


2 Answers

To parse JSON string data using the mongodb java driver 3.x:

Parse JSON document:

Use the Document.parse() static method to parse a single JSON document.

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

Parse JSON array:

Use an instance of BsonArrayCodec to decode a JsonReader.

For example:

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

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

like image 182
NickF Avatar answered Sep 18 '22 23:09

NickF


A simple trick to parse any JSON and to get either Document or List<Document>:

Document.parse("{\"json\":" + json + "}").get("json")
like image 38
Oleg Nitz Avatar answered Sep 17 '22 23:09

Oleg Nitz