Json.NET deserializing Mongo ObjectId is giving the wrong result

前端 未结 1 1096
梦如初夏
梦如初夏 2021-01-03 04:24

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, wh

相关标签:
1条回答
  • 2021-01-03 04:50

    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.

    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>());
    }
    
    0 讨论(0)
提交回复
热议问题