deserialize classes which inherit from superclass with Json.NET?

后端 未结 1 1026

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

1条回答
  •  爱一瞬间的悲伤
    2020-12-21 16:58

    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
     {
         private IContractResolver resolver;
    
         public MembaseJsonSerializer(IContractResolver resolver)
         {
             this.resolver = resolver; 
         }
    
    
        public R FromJson(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.

    0 讨论(0)
提交回复
热议问题