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
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();
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).
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();
}