MVC4 WebApi Serialize / Deserialize MongoDB ObjectId

I am using MVC4 WebApi with the RestSharp client and I am trying to get ObjectIds to serialize (or deserialize) correctly.

I have a base class:

public class User { [BsonId] public ObjectId Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 

What is the best / right way to deserialize this object on the client? All I tried, the Id property is set to ObjectId.Empty.

Many thanks.

Update:

I tried to create another ObjectIdDeserializers. The following is an example of a deserializer and client and a sample json that is sent back to the client.

 public class ObjectIdDeserializer : IDeserializer { public string RootElement { get; set; } public string Namespace { get; set; } public string DateFormat { get; set; } public T Deserialize<T>(RestSharp.IRestResponse response) { return BsonSerializer.Deserialize<T>(response.Content); } } 

In RestSharp, I added the following line to invoke the aforementioned deserializer:

 _client.AddHandler("application/json", new ObjectIdDeserializer()); 

And the json example looks like this:

 "User": { "Id": { "_timestamp":1339158960, "_machine":7962014, "_pid":4040, "_increment":9499872 }, "FirstName":"Test", "LastName":"User" } 
+4
source share
1 answer

After doing a search in SO, I was able to find a simple solution for what I was trying to do.

Using the approach in this answer, the property will be stored as ObjectId, and in the code it's just a string. Exactly what I was hoping to achieve.

fooobar.com/questions/322823 / ...

+3
source

All Articles