派生类型的JSON反序列化 [英] JSON deserialization of derived types
问题描述
class Attribute1
{
}
class Attribute2 : Attribute1
{
}
class class1
{
Attribute1 attr1;
}
class class2 : class1
{
Attribute2 attr2;
}
var serializerSettings = new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.Objects};
class2 a = SomeValidObjectoftype Class2;
string serializedClass2 = JsonConvert.SerializeObject(a, serializerSettings);
var am = JsonConvert.DeserializeObject<Class2>(serializedClass1);
以上所有都是JSON属性和对象.我想做的是序列化和反序列化,而不会丢失类型.
反序列化时,我丢失了am.attr2的类型.目前,它以Attribute1
的形式返回.我希望它为Attribute2
.那可能吗?如果是这样的话,有人可以指出我正确的做法.我加入了SerializationSettings,但仍然遇到相同的问题.
All the above are JSON properties and objects. What I am trying to do is serialize and deserialize and not lose the type.
While deserializing I lose the type of am.attr2. Currently it is coming back as Attribute1
. I want it as Attribute2
. Is that possible? If so could someone point me to the right way of doing it. I included SerializationSettings and still hit the same issue.
推荐答案
在反序列化和序列化时,您必须通过TypeNameHandling = TypeNameHandling.Objects
(或All
或Auto
):
You have to pass TypeNameHandling = TypeNameHandling.Objects
(or All
or Auto
) when deserializing as well as serializing:
var am = JsonConvert.DeserializeObject<Class2>(serializedClass1, serializerSettings );
我认为这是出于安全原因:这意味着使用默认设置在反序列化期间无法注入意外类型.从 docs :
I believe this is for security reasons: it means that an unexpected type cannot be injected during deserialization using default settings. From the docs:
TypeNameHandling
在您的应用程序中应谨慎使用 从外部源反序列化JSON.传入类型应为 使用自定义SerializationBinder
进行了验证,TypeNameHandling.None
以外的值.
TypeNameHandling
should be used with caution when your application deserializes JSON from an external source. Incoming types should be validated with a customSerializationBinder
when deserializing with a value other thanTypeNameHandling.None
.
有关此警告的必要性的讨论,请参见 Newtonsoft Json中的TypeNameHandling警告 .
For a discussion of the need for this caution see TypeNameHandling caution in Newtonsoft Json.
示例小提琴.
这篇关于派生类型的JSON反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!