【发布时间】:2018-09-04 14:56:03
【问题描述】:
我得到了这样的东西
MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase(db);
MongoCollection<Document> collection = database.getCollection(col);
FindIterable<Document> results = collection.find();
我可以使用以下方法获取 JSONArray 字符串:
JSON.serialize(results)
但在最新版本的 mongodb 驱动程序中已弃用。
在 MongoDB shell 中我可以使用:
db.$.find().toArray();
但我在 Java 的驱动程序中没有找到类似的东西。
我使用 List 并遍历光标解决了问题。
MongoCursor<Document> cursor = results.iterator();
List<String> list = new ArrayList<String>();
while(cursor.hasNext())
list.add(cursor.next().toJson());
return list.toString();
请随意提出更好的解决方案。
【问题讨论】:
-
您正在做的事情(在每个
Document上迭代和调用toJson())是使用JSON实用程序类的推荐替代品。来自the commit which deprecated that class:“应用程序应该用 JsonReader、JsonReader 和包装它们的 BasicDBObject 上的 toJson/parse 方法替换它的使用。”。