簡體   English   中英

c# MongoDB BsonDocument - 序列化為 json 作為鍵對象

[英]c# MongoDB BsonDocument - Serialize to json as key-object

我懷疑是否可以將 BsonDocument 結果集合序列化為 json 鍵對象對。

例如,我附上了一段代碼,該代碼創建了一個 BsonDocument 集合,其中包含 _id 和 name 作為字段,

using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExampleBsonDocumentSerializeToJsonAsArray
{
    class Program
    {
        static void Main(string[] args)
        {
            BsonDocument[] data = new BsonDocument[]{

                new BsonDocument {
                        { "_id" , "1" },
                        { "name" , "name_1" },
                        { "description" , "description_1" },
                }
                ,new BsonDocument {
                        { "_id" , "2" },
                        { "name" , "name_2" },
                        { "description" , "description_2" },
                }
                ,new BsonDocument {
                        { "_id" , "3" },
                        { "name" , "name_3" },
                        { "description" , "description_3" },
                }
            };

            Console.WriteLine(data.ToJson());
        }
    }
}

清單 1.1

顯示列表 1.1 中的部分,它給出了一個 json 對象數組的輸出,

[{
    "_id": "1",
    "name": "name_1",
    "description": "description_1"
}, {
    "_id": "2",
    "name": "name_2",
    "description": "description_2"
}, {
    "_id": "3",
    "name": "name_3",
    "description": "description_3"
}]

將字段“_id”作為集合的鍵,我想序列化為一組鍵對象 json 而不是對象數組。 序列化json的結果應該是這樣的,

{
    "1": {
        "name": "name_1"
      , "description": "description_1"
    },
    "2": {
        "name": "name_2"
      , "description": "description_2"
    },
    "3": {
        "name": "name_3"
      , "description": "description_3"
    }
}

我不知道這是否可能

您可以通過System.LinqBsonDocument轉換為Dictionary

using System.Linq;
var kvp = data.AsEnumerable()
    .ToDictionary(x => x["_id"], x => new { name = x["name"], description = x["description"] });
        
Console.WriteLine(kvp.ToJson());

示例程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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