Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
631 views
in Technique[技术] by (71.8m points)

serialization - deserialize classes which inherit from superclass with Json.NET?

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.");
    }
 }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...