【问题标题】:Is it possible to deserialize a "ISODate" field of MongoDB to a JToken (C#) ?是否可以将 MongoDB 的“ISODate”字段反序列化为 JToken (C#)?
【发布时间】:2015-06-20 06:26:09
【问题描述】:

范围:

我正在写set of tools 来帮助人们在他们的 MongoDB 数据库上运行常见操作,“导出”数据就是其中之一。

目前我支持完整的 JSON 导出和“CSV”,但后者更复杂。

导出工具允许使用“ConfigFile”指定哪些字段将被反序列化(来自BsonDocument),而不关心它们的类型。大多数类型目前都在工作,但“ISO”日期仍然让我头疼。

动态反序列化

目前我依靠JObjects 来处理“Json”文档的解析,就像这样:

        // Json Writer Settings - To avoid problems with 10Gen types
        var jsonSettings = new JsonWriterSettings () { OutputMode = JsonOutputMode.Strict };

        // Mapping string to a dynamic json object
        JObject mappedJson = JObject.Parse (jsonObject.ToJson (jsonSettings));
        
        // Trying to extract property values out of the object
        foreach (Field field in _configuration.Fields)
        {
                // Checking for JToken Type
                JTokenType objType = fieldData.Type;
                
                // Sanity Check for NULL Values of properties that do exist
                if (objType == JTokenType.Null)
                {
                    fieldValue = String.Empty;
                }
                else if (objType == JTokenType.Array) // Checking for Arrays (that need to be serialized differently)
                {
                    String[] valuesArray = fieldData.Select (t => t.Value<String> ().Replace (_configuration.ListDelimiter, String.Empty)
                                                                                    .Replace (_configuration.Delimiter, String.Empty)).ToArray ();

                    fieldValue = String.Join (_configuration.ListDelimiter, valuesArray);
                }
                else if (objType == JTokenType.Object && field.Name.Equals ("_id")) // Checking for specific MongoDB "_id" situation
                {
                    fieldValue = fieldData.ToObject<String> (); // Value<ObjectId> ().ToString ();
                }
                else
                {
                    // Reaching Attribute Value as "String" (if nothing else worked)
                    fieldValue = fieldData.Value<String> ();
                }
        }

问题:

此代码适用于我迄今为止测试过的所有类型,但“DateTime”除外。 MongoDB存储的方式如下:"PublicationDate" : ISODate("2014-08-10T00:00:00.000Z"),完全破坏了我的反序列化。

我尝试将其反序列化为“DateTime”和“Object”,但它们都无法正常工作。有什么合适的方法吗?这基本上是我让这个“动态导出器”工作所缺少的。

提前致谢

【问题讨论】:

  • 由于您的工具正在控制 JSON 输出,您应该能够以更标准的格式将日期导出为 JSON;请参阅此处了解如何操作:stackoverflow.com/questions/21466446/…
  • 表达式 ISODate("2014-08-10T00:00:00.000Z") 在 Json 中无效。您可以在 json.org 看到 Json 定义。 Json.Net 支持一些扩展,例如 cmets,但日期不在 Json 定义中。你有想要用 Json.NET 解析的 Json 的完整示例吗?

标签: c# json mongodb serialization json.net


【解决方案1】:

try catch 可能是捕获 iso datetime 的一种不好的解决方案?喜欢JTokenType.Date

using System.Globalization;

public static void ParseMongoDBISODate()
{
    // Json Writer Settings - To avoid problems with 10Gen types
    var jsonSettings = new JsonWriterSettings() { OutputMode = JsonOutputMode.Strict };

    // Mapping string to a dynamic json object
    JObject mappedJson = JObject.Parse(jsonObject.ToJson(jsonSettings));

    // Trying to extract property values out of the object
    foreach (Field field in _configuration.Fields)
    {
        // Checking for JToken Type
        JTokenType objType = fieldData.Type;

        // Sanity Check for NULL Values of properties that do exist
        if (objType == JTokenType.Null)
        {
            fieldValue = String.Empty;
        }
        // Checking for Arrays (that need to be serialized differently)
        else if (objType == JTokenType.Array)
        {
            String[] valuesArray = fieldData.Select(t => t.Value<String>().Replace(_configuration.ListDelimiter, String.Empty).Replace(_configuration.Delimiter, String.Empty)).ToArray();

            fieldValue = String.Join(_configuration.ListDelimiter, valuesArray);
        }
        // Checking for specific MongoDB "_id" situation
        else if (objType == JTokenType.Object && field.Name.Equals("_id"))
        {
            fieldValue = fieldData.ToObject<String>(); // Value<ObjectId> ().ToString ();
        }
        else
        {
            try // it's a bad way but you can set fieldValue as a DateTime
            {
                //JTokenType.Date
                DateTime mongoDBISODate = DateTime.Parse(fieldData.Value<String>(), null, DateTimeStyles.RoundtripKind);
                fieldValue = mongoDBISODate;
            }
            catch (Exception)
            {
                // Reaching Attribute Value as "String" (if nothing else worked)
                fieldValue = fieldData.Value<String>();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多