我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)从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 ;
}
Run Code Online (Sandbox Code Playgroud)我还尝试使用另一个JSON序列化程序(我使用了Google的序列化程序),但它没有提供与toJson()Document对象中的内置方法相同的结果,特别是对于"_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));
Run Code Online (Sandbox Code Playgroud)
将"列表"添加到另一个DBObject与输出中使用的键"列表" 没有任何问题.否则,您可以深入研究使用另一个JSON解析器并将每个文档从游标迭代器提供给它.
这取决于您输入的大小,但是这仍然有效,它确实在代码中看起来更清晰.
| 归档时间: |
|
| 查看次数: |
12513 次 |
| 最近记录: |