Handling MongoDB's ISODate() when attempting to parse a serialized JSON string

前端 未结 6 1798
庸人自扰
庸人自扰 2021-02-07 11:00

I\'m using MongoDB via the official C# driver with an ASP.NET MVC web site.

I have the following C# model:

public class Contact
{
    public ObjectId Id          


        
相关标签:
6条回答
  • 2021-02-07 11:13

    as @Louie Almeda suggests, i think the best approach is with the BsonTypeMapper.MapToDotNetValue. BsonTypeMapperOptions can be customized too.

    Here's what i'm using to convert a list on BsonDocument to a json string using LINQ and newtonsoft serializer :

    var jsonString = JsonConvert.SerializeObject(bsonDocuments.ConvertAll(d => BsonTypeMapper.MapToDotNetValue(d)), Formatting.Indented)
    
    0 讨论(0)
  • 2021-02-07 11:16
     var IDict = v as IDictionary<string, object>;
                            var dict = IDict.ToDictionary(x => x.Key, x => x.Value);
                            var dateVal = dict["$date"];
                            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                            var dateTimeVal = epoch.AddMilliseconds(Convert.ToDouble(dateVal));
    
    0 讨论(0)
  • 2021-02-07 11:27

    I think you need to tweak your JSON serializer a bit more. Try this:

    var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
    Console.WriteLine(document.ToJson(jsonWriterSettings));
    
    0 讨论(0)
  • 2021-02-07 11:28

    You SHOULD use JsonConvert to properly convert the Date to Json. the accepted answer produces a date object like: { $date: 190012312211 } as @Rick Strahl mentioned. This should work:

    object val = BsonTypeMapper.MapToDotNetValue(bsonDocument);
    string jsonString = JsonConvert.SerializeObject(val);
    
    0 讨论(0)
  • 2021-02-07 11:31

    If the JSON data is safe for eval (since its coming from your server it probably is) then you can do like so. It's not particularly pretty, but it gets the job done.

    http://jsfiddle.net/CVLhx/

    var str = '{"_id"  : ObjectId("52eaad4839b60812fca4bf28"),"Name": "Joe Blow","DateAdded" : ISODate("2014-01-30T19:51:35.977Z")}';
    
    function ObjectId(id) { return id;}
    function ISODate(d) {return d;}
    
    var obj = eval('(' + str + ')');
    console.log(obj);
    
    0 讨论(0)
  • 2021-02-07 11:32

    I realize that I am very late to this party but I'll post an answer anyway in case somebody else comes along looking for a solution (as I did).

    The trick is to let the Mongo db driver do the deserialization:

    var collection = database.GetCollection<Contact>("collection name");
    var contact = collection.Find(Query.EQ("Name", "Joe Blow"));
    

    Now contact will have the expected values.

    0 讨论(0)
提交回复
热议问题