【问题标题】:When converting Json to Bson Document fails to correctly convert date value将 Json 转换为 Bson 文档时无法正确转换日期值
【发布时间】:2017-05-09 10:07:56
【问题描述】:

我正在尝试将 Json 对象转换为 MongoDb BsonDocument,但是在转换后从 Json 对象值的日期转换为字符串而不是日期。以下示例将 BsonValueType 输出为字符串。
有什么方法可以正确转换为 Bson Date 值?

        var newObject = new JObject {
                             { "name", "John" },
                            { "age", 25 },                                
                            { "registeredDate" , "2017-05-09T09:14:06+00:00"},
        };

        BsonDocument bsonObj = BsonDocument.Parse(newObject.ToString());

        Console.WriteLine(bsonObj["registeredDate"].BsonType);
        //Outputs String

【问题讨论】:

    标签: json.net mongodb-.net-driver


    【解决方案1】:

    这并不奇怪,因为您的 JSON 对象的 registeredDate 属性有一个字符串值开头(即使它包含一个格式化为 ISO 日期的值)。

    尝试以下方法之一:

    • 如果您想将newObject 保留为JObject

      var newObject = new JObject
      {
          { "name", "John" },
          { "age", 25 },
          { "registeredDate" , new JRaw(@"new ISODate(""2017-05-09T09:14:06+00:00"")") },
      };                    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      

      这给 MongoDB 的 BsonDocument.Parse 一个提示,即字符串值包含 ISO 时间戳,应转换为日期/时间类型。

    • 如果您对 newObject 使用(强类型)匿名 C# 类型表示满意:

      var newObject = new
      {
          name = "John",
          age = 25,
          registeredDate = DateTime.Parse("2017-05-09T09:14:06+00:00"),
      };
      BsonDocument bsonObj = BsonDocument.Parse(newObject.ToJson());
      

      这完全使 Json.NET 脱离了循环,让 MongoDB 完成所有工作。

    我承认我不知道这些解决方案是否是应该做的事情。我不太了解所涉及的库,无法展示其他(可能更好)的选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 2015-04-09
      相关资源
      最近更新 更多