Bson - 如何将JSON转换为List<Document>,以及将List<Document>转换为JSON?

6

我正在使用Java Driver 3.0和MongoDB来通过web服务发送JSON。

当我想将Document对象(org.bson.Document)转换为JSON时,我使用obj.toJson(),而当我想将JSON转换为Document对象时,我使用Document.parse(json)

但是,当我处理Document对象的列表时(在JSON中表示为:[{"field1":1, ...}, {"field1":2, ...}]),我无法找到一个清晰的方法来进行这些转换。

目前,我想到了以下“技巧”:

  • From List to JSON: I add the list of documents as a value of a field called "list" in a bigger document. I convert this big document to JSON, and remove what I don't need from the obtained 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);
    }
    
  • From JSON to List: I do the opposite by adding this "list" field to the JSON, converting it to a Document and getting only the value of this field from the 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"字段或时间戳。

有没有干净的方法来做到这一点?

2个回答

9

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));

将“列表”添加到另一个DBObject中,键为“list”,并将其用于输出是没有问题的。否则,您可以深入使用另一个JSON解析器,并将游标迭代器中的每个文档馈送到其中。

这取决于您的输入大小,但在代码中,虽然这仍然有效,但看起来更加简洁。


谢谢你的回答,但我想知道是否有适用于驱动程序3.0的解决方案。 不过,我不知道我可以使用BasicDBList与文档一起使用,而不是DBObject,所以谢谢。我猜我可以做相反的事情,将JSON转换为List<Document>? - Thematrixme
@Thematrixme,你有没有看到“is not deprecated”声明?这意味着它可以与当前的驱动程序一起使用。还有其他使用外部库的方法。但是,没有更新的“util”包可以原生地与BSON Document一起使用。只需转换类型即可。 - Blakes Seven
我知道“已弃用”是什么意思,但我担心在下一个版本中会被删除,就像你提到的“仍未弃用”,我希望有一个原生的解决方案适用于驱动程序3.0。然而,由于目前还没有这样的东西,你的答案似乎是正确的。谢谢! - Thematrixme
@Thematrixme,我在这里并不是要“居高临下”,所以希望你不要这样理解,我使用了一个术语,因此我认为你能够理解。我的观点是“未被弃用”。因此,当它被标记并且您的构建开始显示警告时,请担心它。正如我之前所说,还有其他可以处理此问题的JSON库,以及一些深入的BSON文档编组钩子。我猜测在未来的驱动程序发布中会有更好的方法。但现在,我建议坚持使用有效且“简单”的方法。干杯。 - Blakes Seven

1

有关驱动程序3.0的解决方案。

您可以按照以下步骤操作:

BasicDBObject dbObject = (BasicDBObject) JSON.parse("yourJsonString");
MongoCollection<BasicDBObject> table = db.getCollection("collectionName", BasicDBObject.class);
table.insertOne(dbObject);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接