简体   繁体   English

Bson - 如何将JSON转换为List <Document>并将List <Document>转换为JSON?

[英]Bson - How to convert JSON to List<Document> and List<Document> to JSON?

I'm using Java Driver 3.0 with MongoDB in order to send JSONs through a webservice. 我正在使用Java Driver 3.0和MongoDB,以便通过Web服务发送JSON。

When I want to convert a Document object (org.bson.Document) to JSON, I use obj.toJson() , and when I want to convert a JSON to a Document object, I use Document.parse(json) . 当我想将Document对象(org.bson.Document)转换为JSON时,我使用obj.toJson() ,当我想将JSON转换为Document对象时,我使用Document.parse(json)

However when I'm dealing with lists of Documents (represented like this in JSON: [{"field1":1, ...}, {"field1":2, ...}] ), I can't figure out a clean way of doing these conversions. 但是,当我处理文档列表(在JSON中表示如此: [{"field1":1, ...}, {"field1":2, ...}] )时,我无法弄清楚这种转换的干净方式。

So far, I've come up with these "hacks": 到目前为止,我已经提出了这些“黑客”:

  • From List to JSON: I add the list of documents as a value of a field called "list" in a bigger document. 从List到JSON:我将文档列表添加为更大文档中名为“list”的字段的值。 I convert this big document to JSON, and remove what I don't need from the obtained String. 我将这个大文档转换为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); } 
  • 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. 从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 ; } 

I also tried to use another JSON serializer (I took Google's one), but it doesn't give the same result as the built-in toJson() method from the Document object, particularly for the "_id" field or the timestamps. 我还尝试使用另一个JSON序列化程序(我使用了Google的一个),但是它没有提供与Document对象中内置的toJson()方法相同的结果,特别是对于“_id”字段或时间戳。

Is there any clean way of doing this? 这样做有什么干净的方法吗?

The com.mongodb.util.JSON package is "still" not deprecated and does handle lists of DBObject quite well. com.mongodb.util.JSON包“仍然”不被弃用,并且可以很好地处理DBObject列表。 You just need to do a little converting: 你只需要做一点转换:

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

And there is nothing wrong with adding that "list" to another DBObject wih the key "list" as used in your output. 将“list”添加到另一个DBObject中与输出中使用的键“list”没有任何关系。 Otherwise you can delve into using another JSON parser and feeding each document from the cursor iterator into that. 否则,您可以深入研究使用另一个JSON解析器并将每个文档从游标迭代器提供给它。

It depends on the size of your input, but while this still works it sure looks a lot cleaner in code. 这取决于您输入的大小,但是这仍然有效,它确实在代码中看起来更清晰。

There is solution for driver 3.0. 有驱动程序3.0的解决方案。

You follow the following steps: 您按照以下步骤操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM