java-从JSON字符串创建BSON对象
我有从外部应用程序获取数据的Java应用程序。 传入的JSON以字符串形式。 我想解析该Strings并创建BSON对象。
不幸的是,我在Java的BSON实现中找不到用于此的API。
我是否像GSON这样使用了外部解析器?
9个解决方案
39 votes
官方的MongoDB Java驱动程序附带了实用程序方法,用于将JSON解析为BSON并将BSON序列化为JSON。
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
DBObject dbObj = ... ;
String json = JSON.serialize( dbObj );
DBObject bson = ( DBObject ) JSON.parse( json );
该驱动程序可以在这里找到:[https://mongodb.github.io/mongo-java-driver/]
eskatos answered 2020-07-13T15:28:49Z
38 votes
...而且,从3.0.0版本开始,您可以:
import org.bson.Document;
final Document doc = new Document("myKey", "myValue");
final String jsonString = doc.toJson();
final Document doc = Document.parse(jsonString);
官方文档:
Document.parse(String)
Document.toJson()
yair answered 2020-07-13T15:29:23Z
12 votes
最简单的方法似乎是使用JSON库将JSON字符串解析为Map,然后使用Map方法将这些值放入BSONObject。
此答案显示了如何使用Jackson来将JSON字符串解析为Map。
Hank Gay answered 2020-07-13T15:28:24Z
10 votes
要将字符串json转换为bson,请执行以下操作:
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);
要将bson转换为json,请执行以下操作:
import org.bson.BasicBSONDecoder;
import org.bson.BSONObject;
BasicBSONDecoder decoder = new BasicBSONDecoder();
BSONObject bsonObject = decoder.readObject(out);
String json_string = bsonObject.toString();
Leticia Santos answered 2020-07-13T15:29:48Z
5 votes
使用org.bson.Document中的Document.parse(String json)。它返回Document对象,其类型为Bson。
ultimatex answered 2020-07-13T15:30:08Z
3 votes
您可能对bson4jackson项目感兴趣,该项目使您可以使用Jackson数据绑定来与BSON一起使用(从BSON创建POJO,写为BSON)-尤其是因为Jackson也与JSON一起工作。 因此,它将允许您进行转换,只需要使用不同的ObjectMapper实例即可(一种适用于JSON,另一种适用于BSON)。
使用Jackson,您可以使用完整的POJO(所需的声明结构),也可以使用简单的Map,List等。 您只需要声明读取数据时绑定到的类型(写入时,类型由您传递的对象定义)。
StaxMan answered 2020-07-13T15:30:34Z
2 votes
您可以在[https://github.com/mongodb/mongo/blob/master/src/mongo/db/jsobj.cpp]的源代码中找到问题的答案。其中具有从BSON到JSON的转换。
基本上,像
/XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }
/XXX/gi -> { "$regex" : "XXX", "$options" : "gi" }
等等...
Kresten Krab Thorup answered 2020-07-13T15:32:08Z
2 votes
我建议使用BasicDBObject的toJson()和parse(String)方法,因为JSON实用程序类已@Depricated。
import com.mongodb.BasicDBObject;
public static BasicDBObject makeBsonObject(String json) {
return BasicDBObject.parse(json);
}
public static String makeJsonObject(BasicDBObject dbObj) {
return dbObj.toJson();
}
user2023448 answered 2020-07-13T15:32:28Z
1 votes
我不确定Java,但是mongoDB CPP驱动程序具有函数类型
BSONObj fromjson(字符串)
它根据传递的字符串返回BSONObj。 Java也应该有相同的功能。
mayank_gupta answered 2020-07-13T15:32:57Z