Json.NET反序列化Mongo ObjectId给出错误的结果 [英] Json.NET deserializing Mongo ObjectId is giving the wrong result

查看:86
本文介绍了Json.NET反序列化Mongo ObjectId给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是官方的Mongo C#驱动程序,并使用RestSharp使用Json.NET调用Rest Api来执行我的序列化/反序列化.假设我有一个Person类,如下所示,我想对其进行POST& GET:

I'm using the official Mongo C# Driver, and RestSharp to call a Rest Api with Json.NET to perform my serialization/deserialization. Say I have a Person class as follows, which I'd like to POST & GET:

public class Person
{
  [JsonProperty("_id"),JsonConverter(typeof(ObjectIdConverter))]
  public ObjectId Id {get;set;}
  public string Name {get;set;}
}

我创建一个新的Person对象:

I create a new Person object:

var person = new Person{Id = ObjectId.GenerateId(),Name='Joe Bloggs'};

将其发布,然后在服务器上看到以下正确信息:

POST it, and on the server I see the following which is correct:

{ _id: 52498b56904ee108c99fbe88, name: 'Joe Bloggs'}

问题是,当我执行GET时,我在客户端获得的ObjectId是{0000000000000 ...} 即不是我所期望的{5249 .....}.原始响应显示正确的值,但是一旦我反序列化,我就会失去它.

The problem, is when I perform a GET the ObjectId I get on the client is {0000000000000...} i.e. not the {5249.....} I'd expect. The raw response is showing the correct value, but once I deserialize I loose it.

ObjectIdConverter代码是:

The ObjectIdConverter code is :

public class ObjectIdConverter : JsonConverter
{
   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
      serializer.Serialize(writer, value.ToString());
   }

   public override object ReadJson(JsonReader reader, Type objectType, object  existingValue, JsonSerializer serializer)
   {
     var objectId = (ObjectId)existingValue; // at this point existingValue is {000...}
     return objectId;
   }

   public override bool CanConvert(Type objectType)
   {
     return (objectType == typeof (ObjectId));
   }
}

任何帮助将不胜感激.

推荐答案

您正在错误地实现转换器的ReadJson方法. existingValue参数不会为您提供从JSON读取的反序列化值,它会为您提供您将要替换的对象的现有值.在大多数情况下,该值为null或为空.您需要做的是使用reader从JSON获取值,根据需要对其进行转换,然后返回转换后的值.

You are implementing the ReadJson method of the converter incorrectly. The existingValue parameter does not give you the deserialized value read from the JSON, it gives you the existing value of the object that you will be replacing. In most cases this will be null or empty. What you need to do is use the reader to get the value from the JSON, convert it as needed, then return the converted value.

假设您的ObjectId类具有一个接受十六进制字符串的构造函数,这是实现ReadJson方法的方法:

Assuming your ObjectId class has a constructor that accepts a hex string, here is how you would implement the ReadJson method:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    JToken token = JToken.Load(reader);
    return new ObjectId(token.ToObject<string>());
}

这篇关于Json.NET反序列化Mongo ObjectId给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆