c# - 在 MongoDB 中使用嵌套数组保存字典

标签 c# mongodb serialization json.net mongodb-.net-driver

以下类应由 API 作为 Json 接收,并使用 C# 驱动程序和 Web API 存储在 MongoDB 中。数据属性是非结构化的,但我可以将其限制为键值对,这些值中可能包含嵌套数组。

public class Something
{
    [BsonId, JsonIgnore]
    public ObjectId _id { get; set; }

    public IDictionary<string, object> data { get; set; }
}

当从客户端发布 json 时,Json.NET 会正确反序列化。

将类保存到 MongoDB,我在数据库中得到类似这样的 C# 特定类型的内容:

{
    property1: 'one',
    property2: {
        _t: 'System.Collections.Generic.List`1[System.Object]'
        _v:
        [
            {}, {}, {}, ...
        ]
     }
}

基于这些来源,我为 Json.NET 整合了一个 CustomCreationConverter,它将一个 List 嵌套到 Dictionary 的值中:

Apply JsonDictionaryAttributes to properties

Json.NET: Deserializing nested dictionaries

CustomCreationConverter Source Code

public class Something
{
    ...
    [JsonProperty(ItemConverterType = typeof(CustomConverter))]
    public IDictionary<string, object> data { get; set; }
}

使用此覆盖:

public class CustomConverter : CustomCreationConverter<IList<object>>
{
    public override IList<object> Create(Type objectType)
    {
        return new List<object>();
    }

    public override bool CanConvert(Type objectType)
    {
        return true; // Just to keep it simple
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartArray)
            return base.ReadJson(reader, objectType, existingValue, serializer);

        return serializer.Deserialize(reader);
    }
}

这实际上工作正常,但我仍然在 MongoDB 中使用 c# 特定类型进行构造。嵌套时如何在没有类型值属性的情况下将这些数据导入 MongoDB?

最佳答案

所以我有这个与 Dictionary<> 一起工作而不是 IDictionary<>没有自定义转换器,但我也使用自己的类型而不仅仅是 object .我不清楚你所说的“有用的方式”是什么意思,但你可以用 BsonDictionaryOptionsAttribute 注释你的成员并传入 DictionaryRepresentation.DocumentDictionaryRepresentation.ArrayOfDocument如果这就是您的意思,则更改保存到 MongoDB 的形状?

否则,关于它现在的结构方式,您所说的“有用的方式”是什么意思?你总是会得到 "_t"鉴别器,只要有不止一种可能的类型。我猜你看到那个是因为你正在使用 IDictionary<> .

关于c# - 在 MongoDB 中使用嵌套数组保存字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396194/

相关文章:

c# - iTextSharp 在 Winforms 项目中不起作用

node.js - Put 方法不在后端使用 NodeJS 更新 Angular7 中的 MongoDB

mongodb - 如何使用 MongoDB 进行报告?

java.io.StreamCorruptedException : invalid stream header: 00000000

c# - 在 C# 上登录用户后注销

c# - 实现 BindingList<T>

node.js - $ 或使用 Mongoose 搜索

serialization - 是什么让 Smalltalk 能够进行图像持久化,为什么像 Ruby/Python 这样的语言不能序列化自己?

c# - 带有 List<T> 的 SerializationBinder

c# - 如何在 ControllerContext 中模拟 DisplayMode 以进行单元测试 c#