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

Ben*_* E. 5 c# serialization json.net mongodb mongodb-.net-driver

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

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

    public IDictionary<string, object> data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

将类保存到 MongoDB,我在具有 c# 特定类型的数据库中得到类似的信息:

{
    property1: 'one',
    property2: {
        _t: 'System.Collections.Generic.List`1[System.Object]'
        _v:
        [
            {}, {}, {}, ...
        ]
     }
}
Run Code Online (Sandbox Code Playgroud)

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

将 JsonDictionaryAttributes 应用于属性

Json.NET:反序列化嵌套字典

CustomCreationConverter 源代码

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

使用此覆盖:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

cir*_*rus 3

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

否则,就其现在的结构方式而言,“有用的方式”是什么意思?"_t"只要有不止一种可能的类型,您总是会得到鉴别器。我猜您看到这一点是因为您正在使用IDictionary<>.