Creating BSON object from JSON string

前端 未结 9 1683
眼角桃花
眼角桃花 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 04:05

    To convert a string json to bson, do:

    import org.bson.BasicBSONEncoder;
    import org.bson.BSONObject;
    
    BSONObject bson = (BSONObject)com.mongodb.util.JSON.parse(string_json);
    BasicBSONEncoder encoder = new BasicBSONEncoder();
    byte[] bson_byte = encoder.encode(bson);
    

    To convert a bson to json, do:

    import org.bson.BasicBSONDecoder;
    import org.bson.BSONObject;
    
    BasicBSONDecoder decoder = new BasicBSONDecoder();
    BSONObject bsonObject = decoder.readObject(out);
    String json_string = bsonObject.toString();
    

提交回复
热议问题