Creating BSON object from JSON string

前端 未结 9 1641
眼角桃花
眼角桃花 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();
    
    0 讨论(0)
  • 2020-12-01 04:11

    You might be interested in bson4jackson project, which allows you to use Jackson data binding to work with BSON (create POJOs from BSON, write as BSON) -- especially since Jackson also work with JSON. So it will allow conversion like you mention, just use different ObjectMapper instanstaces (one that works with JSON, other with BSON).

    With Jackson you can either work with full POJOs (declare structure you want) or with simple Maps, Lists and so on. You just need to declare what to type to bind to when reading data (when writing, type is defined by object you pass).

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

    I would suggest using the toJson() and parse(String) methods of the BasicDBObject, because the JSON utility class has been @Depricated.

    import com.mongodb.BasicDBObject;
    
    public static BasicDBObject makeBsonObject(String json) {
        return BasicDBObject.parse(json);
    }
    
    public static String makeJsonObject(BasicDBObject dbObj) {
        return dbObj.toJson();
    }
    
    0 讨论(0)
提交回复
热议问题