Creating BSON object from JSON string

2022-08-31 16:50:46

I have Java app that takes data from external app. Incoming JSONs are in Strings. I would like to parse that Strings and create BSON objects.

Unfortunate I can't find API for that in Java's BSON implementation.

Do I have use external parser for that like GSON?


答案 1

... And, since 3.0.0, you can:

import org.bson.Document;

final Document doc = new Document("myKey", "myValue");
final String jsonString = doc.toJson();
final Document doc = Document.parse(jsonString);

Official docs:


答案 2

Official MongoDB Java Driver comes with utility methods for parsing JSON to BSON and serializing BSON to JSON.

import com.mongodb.DBObject;
import com.mongodb.util.JSON;

DBObject dbObj = ... ;
String json = JSON.serialize( dbObj );
DBObject bson = ( DBObject ) JSON.parse( json );

The driver can be found here: https://mongodb.github.io/mongo-java-driver/