MVC4 WebApi序列化/反序列化MongoDB ObjectId [英] MVC4 WebApi Serialization/Deserialization MongoDB ObjectId
问题描述
我正在将MVC4 WebApi与RestSharp客户端一起使用,并且正在努力获取ObjectId以正确地序列化(或反序列化).
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; }
}
在客户端上反序列化此对象的最佳/正确方法是什么?我尝试过的所有Id属性都具有ObjectId.Empty值.
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.
我尝试创建一个不同的ObjectIdDeserializers.下面是反序列化器和客户端的示例,并将示例json发送回客户端.
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);
}
}
在RestSharp中,我添加了以下行来调用上述反序列化器:
In RestSharp I have added the following line to call the above deserializer:
_client.AddHandler("application/json", new ObjectIdDeserializer());
一些示例json看起来像这样:
And some sample json looks like this:
"User":
{
"Id":
{
"_timestamp":1339158960,
"_machine":7962014,
"_pid":4040,
"_increment":9499872
},
"FirstName":"Test",
"LastName":"User"
}
推荐答案
在SO上进行了大量搜索之后,我能够找到自己想做的简单解决方案.
After doing a bunch of searching on SO, I was able to find a simple solution for what I was trying to do.
使用此答案中的方法,该属性将存储为ObjectId,而在代码中它只是一个字符串.正是我希望达到的目标.
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
这篇关于MVC4 WebApi序列化/反序列化MongoDB ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!