簡體   English   中英

Bson - 如何將JSON轉換為List <Document>並將List <Document>轉換為JSON?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM