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 ?
To parse JSON string data using the mongodb java driver 3.x:
Use the Document.parse()
static method to parse a single JSON document.
Document doc = Document.parse("{\"objA\":{\"foo\":1}}");
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
A simple trick to parse any JSON and to get either Document
or List<Document>
:
Document.parse("{\"json\":" + json + "}").get("json")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With