派生类型的JSON反序列化 [英] JSON deserialization of derived types

查看:102
本文介绍了派生类型的JSON反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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(或AllAuto):

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 custom SerializationBinder when deserializing with a value other than TypeNameHandling.None.

有关此警告的必要性的讨论,请参见 Newtonsoft Json中的TypeNameHandling警告 .

For a discussion of the need for this caution see TypeNameHandling caution in Newtonsoft Json.

示例小提琴.

这篇关于派生类型的JSON反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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