[英]Bson - How to convert JSON to List<Document> and List<Document> to JSON?
我正在使用Java Driver 3.0和MongoDB,以便通过Web服务发送JSON。
当我想将Document对象(org.bson.Document)转换为JSON时,我使用obj.toJson()
,当我想将JSON转换为Document对象时,我使用Document.parse(json)
。
但是,当我处理文档列表(在JSON中表示如此: [{"field1":1, ...}, {"field1":2, ...}]
)时,我无法弄清楚这种转换的干净方式。
到目前为止,我已经提出了这些“黑客”:
从List到JSON:我将文档列表添加为更大文档中名为“list”的字段的值。 我将这个大文档转换为JSON,并从获取的String中删除我不需要的内容。
public String toJson(List<Document> docs){ Document doc = new Document("list", docs); String json = doc.toJson(); return json.substring(json.indexOf(":")+2, json.length()-1); }
从JSON到List:我通过将此“list”字段添加到JSON,将其转换为Document并仅从Document获取此字段的值来执行相反的操作。
public static List<Document> toListOfDocuments(String json){ Document doc = Document.parse("{ \\"list\\":"+json+"}"); Object list = doc.get("list"); if(list instanceof List<?>) { return (List<Document>) doc.get("list"); } return null ; }
我还尝试使用另一个JSON序列化程序(我使用了Google的一个),但是它没有提供与Document对象中内置的toJson()
方法相同的结果,特别是对于“_id”字段或时间戳。
这样做有什么干净的方法吗?
com.mongodb.util.JSON
包“仍然”不被弃用,并且可以很好地处理DBObject
列表。 你只需要做一点转换:
MongoClient client = new MongoClient(new ServerAddress("192.168.2.4", 27017));
MongoDatabase db = client.getDatabase("test");
MongoCollection<Document> collection = db.getCollection("sample");
MongoCursor<Document> iterator = collection.find().iterator();
BasicDBList list = new BasicDBList();
while (iterator.hasNext()) {
Document doc = iterator.next();
list.add(doc);
}
System.out.println(JSON.serialize(list));
将“list”添加到另一个DBObject
中与输出中使用的键“list”没有任何关系。 否则,您可以深入研究使用另一个JSON解析器并将每个文档从游标迭代器提供给它。
这取决于您输入的大小,但是这仍然有效,它确实在代码中看起来更清晰。
有驱动程序3.0的解决方案。
您按照以下步骤操作:
BasicDBObject dbObject = (BasicDBObject) JSON.parse("yourJsonString");
MongoCollection<BasicDBObject> table = db.getCollection("collectionName", BasicDBObject.class);
table.insertOne(dbObject);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.