Json.net Deserialize to JObject derived type

╄→гoц情女王★ 提交于 2019-12-11 06:02:07

问题


public class A : JObject
{}

and I have the folowing deserialization code

using (StreamReader responseStreamReader = new StreamReader(stream))
{
    using (JsonReader reader = new JsonTextReader(responseStreamReader))
    {
        JsonSerializer serializer = new JsonSerializer();
        return serializer.Deserialize<A>(reader);
    }
}

But it throws Invalid Cast Exception

in fact the deserializer just need to create new A() instead of new JObject() and do exactly the same after that, it would be enough for me.

How can I deserialize to a more specific JObject type ?


回答1:


You won't be able to deserialize directly to your JObject-derived A class because the internals of Json.Net handle JTokens specially. However, you can easily work around the problem with two small changes to your code.

  1. Add a constructor to your A class which accepts a JObject and passes the same to the base class constructor.

    public class A : JObject
    {
        public A(JObject jo) : base(jo)
        {
        }
    
        public A() : base()
        {
        }
    }
    
  2. In your deserialization method, deserialize to a JObject, then construct your A class from that.

    using (StreamReader responseStreamReader = new StreamReader(stream))
    {
        using (JsonReader reader = new JsonTextReader(responseStreamReader))
        {
            JsonSerializer serializer = new JsonSerializer();
            return new A(serializer.Deserialize<JObject>(reader));
        }
    }
    

Fiddle: https://dotnetfiddle.net/S8d3S6



来源:https://stackoverflow.com/questions/43297664/json-net-deserialize-to-jobject-derived-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!