问题
I am using MVC4 WebApi with a RestSharp client and I am struggling to get ObjectIds to serialize (or deserialize) properly.
I have a basic class like so:
public class User
{
[BsonId]
public ObjectId Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
What is the best/proper way to deserialize this object on the client? Everything I have tried the Id property is of value ObjectId.Empty.
Update
I have tried a creating a different ObjectIdDeserializers. Below is an example of a deserializer and the client and sample json that is being 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 have added the following line to call the above deserializer:
_client.AddHandler("application/json", new ObjectIdDeserializer());
And some sample json looks like this:
"User":
{
"Id":
{
"_timestamp":1339158960,
"_machine":7962014,
"_pid":4040,
"_increment":9499872
},
"FirstName":"Test",
"LastName":"User"
}
回答1:
After doing a bunch of searching on SO, I was able to find a simple solution for what I was trying to do.
Using the approach in this answer, the property gets stored as an ObjectId and in code it is just a string. Exactly what I was hoping to achieve.
https://stackoverflow.com/a/7982411/360843
来源:https://stackoverflow.com/questions/10942824/mvc4-webapi-serialization-deserialization-mongodb-objectid