反序列化使用Json.NET从超类继承的类? [英] deserialize classes which inherit from superclass with Json.NET?

查看:70
本文介绍了反序列化使用Json.NET从超类继承的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题,想知道它是否可以使用json.net

i have a problem and want to know if it is or if it will be possible with json.net

我有一个称为A的超类,以及两个继承自它的类B1和B2 当我列出A类型的列表,然后添加一些B1和B2时,在序列化和反序列化之后,它们都是A类型.

i have a superclass called A and two classes which inherit from it, B1 and B2 when i made a list of type A and then add some B1 and B2, after serialize and deserialize they are all of type A.

是否每个继承的类都将被强制转换为以前的类类型,例如B1或B2?

Is it possible that each class which inherit will be casted to its former class type like B1 or B2?

推荐答案

是的,只要您通知JSON.Net您要使用TypeNameHandling.All并使用适当的强制转换,它就应该起作用.我的项目中有以下作品:

Yes, it should work as long as you inform JSON.Net that you want to use TypeNameHandling.All and use appropriate casting. The following works in my project:

 public class MembaseJsonSerializer<T>
 {
     private IContractResolver resolver;

     public MembaseJsonSerializer(IContractResolver resolver)
     {
         this.resolver = resolver; 
     }


    public R FromJson<R>(object json)
    {
        if (typeof(T).IsAssignableFrom(typeof(R)))
        {
            object res = JsonConvert.DeserializeObject(json.ToString(), new JsonSerializerSettings() { 
                ContractResolver = resolver, 
                TypeNameHandling = TypeNameHandling.All 
            });
            return (R)res;
        }
        throw new NotImplementedException("Type is not assignable.");
    }

    public string ToJson(object obj)
    {
        if (typeof(T).IsAssignableFrom(obj.GetType()))
        {
            string json = JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings()  { 
                ContractResolver = resolver, 
                TypeNameHandling = TypeNameHandling.All 
            });
            return json; 
        }
        throw new NotImplementedException("Type is not assignable.");
    }
 }

其中T是基类,R是子类.

Where T is the base class and R is the sub class.

这篇关于反序列化使用Json.NET从超类继承的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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