Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...