问题
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.
Add a constructor to your
A
class which accepts aJObject
and passes the same to the base class constructor.public class A : JObject { public A(JObject jo) : base(jo) { } public A() : base() { } }
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