Handling MongoDB's ISODate() when attempting t

2019-04-04 14:32发布

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 { get; set; }
    public string Name { get; set; }
    public DateTime DateAdded { get; set; }
}

Which, when pulled from MongoDB and serialized into a JSON string via MVC looks like:

{
    "_id"  : ObjectId("52eaad4839b60812fca4bf28"),
    "Name": "Joe Blow",
    "DateAdded" : ISODate("2014-01-30T19:51:35.977Z")
}

When I attempt to convert this from a JSON string to a Javascript object on the browser via JSON.parse(), I get the following error:

Uncaught SyntaxError: Unexpected token I

This is because ISODate(...) is not valid JSON

ObjectId() is also not valid JSON, but the way I'm handling that is to simply perform a string.replace() on the JSON string prior to parsing it on the client. I considered doing the same for ISODate() but it feels a little too hacky.

Is there something I can do without resorting to regular expressions on the client side? Perhaps something from the MongoDB driver?

6条回答
来,给爷笑一个
2楼-- · 2019-04-04 14:46

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));
查看更多
Rolldiameter
3楼-- · 2019-04-04 14:46

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);
查看更多
做个烂人
4楼-- · 2019-04-04 14:46

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.

查看更多
太酷不给撩
5楼-- · 2019-04-04 14:49

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);
查看更多
Evening l夕情丶
6楼-- · 2019-04-04 14:54
 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));
查看更多
仙女界的扛把子
7楼-- · 2019-04-04 15:04

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)
查看更多
登录 后发表回答