简体   繁体   English

C#/ MongoDB对字典数组的数组进行反序列化

[英]C# / MongoDB Deserialization of Array of Array of Dictionaries

I am attempting to create an array of array of dictionaries in ASP.NET Core using MongoDB. 我正在尝试使用MongoDB在ASP.NET Core中创建字典数组的数组。 In the end, the data should retain this model for all uses: 最后,数据应保留此模型以用于所有用途:

Model 模型

{
    "ContextName": "Base rates",
    "Indexes": [
        {
            "IndexName": "S&P",
            "IndexValues" : [
                {
                    "Date": "2019-01-01",
                    "Value": "2600.98"
                },
                {
                    "Date": "2019-01-02",
                    "Value": "2605.98"
                }              
            ]
        }
    ]
}

Currently, I have my first layer defined below encompassing the ContextName and Indexes : 当前,我在下面定义了第一层,包括ContextNameIndexes

Context.cs Context.cs

public class Context
    {
        [BsonId]
        [BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonElement("ContextName")]
        public string ContextName { get; set; }
        [BsonElement("Indexes")]
        public ICollection<Index> Indexes { get; set; }
    }

With Index having the following structure: Index具有以下结构:

Index.cs Index.cs

public class Index
    {
        [BsonElement("IndexName")]
        public string IndexName { get; set; }
        [BsonElement("IndexValues")]
        [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
        public Dictionary<DateTime, double> IndexValues { get; set; }
    }

Running this code I am met with a Format Exception stating 运行此代码,遇到格式异常说明

An error occurred while deserializing the IndexValues property of class Database.Index: Invalid element: 'Date'.' '反序列化类Database.Index的IndexValues属性时发生错误:无效元素:'Date'。

My first thought is that it is an issue with the key being of type Date and not of string within the database itself, however I have read here towards the bottom that the official driver supports this actually. 我的第一个想法是这是一个问题,该问题的关键是Date类型而不是数据库本身内的string ,但是我在这里已经读到底部 ,官方驱动程序实际上支持此问题。

I went a bit further to try and set some custom { get; set; } 我进一步尝试尝试设置一些自定义{ get; set; } { get; set; } { get; set; } to bring in the key as a string but am being met with the same error in the end. { get; set; }以字符串形式输入密钥,但最后却遇到相同的错误。

public Dictionary<DateTime, double> IndexValues
        {
            get
            {
                Dictionary<DateTime, double> _indexValues = new Dictionary<DateTime, double>();
                foreach (var indexValue in IndexValues)
                {
                    _indexValues.Add(indexValue.Key, indexValue.Value);
                }
                return _indexValues;
            }
            set { IndexValues = IndexValues; } // Unsure about here as well
        }

I am unsure what to be looking at for this case, and am looking for some pointers to figure this out. 我不确定在这种情况下要看什么,并且正在寻找一些提示来解决这个问题。 Thanks in advance. 提前致谢。

Update 更新资料

Formatting the dictionary in an external method allows for the correct format, however also inserts one extra field as it is used in gathering all the required information. 使用外部方法格式化字典可以使用正确的格式,但是由于它用于收集所有必需的信息,因此还会插入一个额外的字段。

public Dictionary<DateTime, double> IndexValuesDictionary
        {
            get { return SetDictionary(); }
            set { SetDictionary(); }
        }

        private Dictionary<DateTime, double> SetDictionary()
        {
            if (_indexValues == null)
            {
                _indexValues = new Dictionary<DateTime, double>();
                foreach (var indexValue in IndexValues)
                {
                    _indexValues.Add(indexValue.Date, indexValue.Value);
                }
            }
            return _indexValues;
        }
{
        "id": "5c93c1123369220b685719b3",
        "contextName": "Base rates",
        "indexes": [
            {
                "indexName": "S&P",
                "indexValues": [
                    {
                        "date": "2019-01-01T00:00:00Z",
                        "value": 2600.98
                    },
                    {
                        "date": "2019-01-02T00:00:00Z",
                        "value": 2605.98
                    }
                ],
                "indexValuesDictionary": { // This should not be included
                    "2019-01-01T00:00:00Z": 2600.98,
                    "2019-01-02T00:00:00Z": 2605.98
                }
            }
        ]
    }

Is this the only viable option for this output? 这是此输出的唯一可行选择吗?

After taking a step back and looking at the data structure, I was able to get this working by removing the array nesting and working solely with document nesting (unfortunate but simplifies the schema). 在退后一步并查看了数据结构之后,我可以通过删除数组嵌套并仅使用文档嵌套来实现此功能(不幸的是,但简化了架构)。 The updated database structure is: 更新后的数据库结构为:

[
    {
        "ContextName": "Base rates",
        "Description": "Base rates description",
        "Indexes": {
            "SPX": {
                "2019-01-01T00:00:00Z": 2600.98
            },
            "NDX": {
                "2019-01-01T00:00:00Z": 6600.98
            }
        }
    }
]

Leaving the class structures updated as: 将类结构更新为:

Context.cs Context.cs

public class Context
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonElement("ContextName")]
        public string ContextName { get; set; }
        [BsonElement("Description")]
        public string Description { get; set; }
        [BsonElement("Indexes")]
        [BsonDictionaryOptions(DictionaryRepresentation.Document)]
        public Index Indexes { get; set; }
    }

Index.cs Index.cs

public class Index : Dictionary<string, Dictionary<DateTime, double>> { }

I also changed the serializer to treat DateTime as a string instead, and so included this in the program startup: 我还更改了序列化程序以将DateTime视为string ,因此将其包含在程序启动中:

BsonSerializer.RegisterSerializer(new DateTimeSerializer(DateTimeKind.Local, BsonType.String));

These changes allow the structure to be formatted correctly. 这些更改允许正确格式化结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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