Creating BSON object from JSON string

前端 未结 9 1640
眼角桃花
眼角桃花 2020-12-01 03:10

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 fi

相关标签:
9条回答
  • 2020-12-01 03:50

    Use Document.parse(String json) from org.bson.Document. It returns Document object which is type of Bson.

    0 讨论(0)
  • 2020-12-01 03:51

    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/

    0 讨论(0)
  • 2020-12-01 03:53

    ... 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:

    • Document.parse(String)
    • Document.toJson()
    0 讨论(0)
  • 2020-12-01 03:53

    I am not sure about java but the mongoDB CPP driver has a function type

    BSONObj fromjson(string)

    which returns a BSONObj according to the string passed. There should be a same function in Java too.

    0 讨论(0)
  • 2020-12-01 04:00

    The easiest way seems to be to use a JSON library to parse the JSON strings into a Map and then use the putAll method to put those values into a BSONObject.

    This answer shows how to use Jackson to parse a JSON string into a Map.

    0 讨论(0)
  • 2020-12-01 04:04

    You'll find the answer to your question in the source code of https://github.com/mongodb/mongo/blob/master/src/mongo/db/jsobj.cpp Which has the BSON to JSON conversion.

    Basically, stuff like

    • ObjectId("XXX") -> { "$oid" : "XXX" }
    • /XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }

    and so on...

    0 讨论(0)
提交回复
热议问题