问题
I use stock JSON serialiser in .NET 4.5 windows store app -
System.Runtime.Serialization.Json.DataContractJsonSerializer
I have a class which is supplied by the API provider say
class A { public DateTime Date {get;set} }
I wanted to hide Date field by doing this (NOTE - new keyword):
class AEx : A { public new string Date {get;set} }
But I am getting exception:
type 'AEx' is not serializable with DataContractJsonSerializer because the data member 'Date' is duplicated in its type hierarchy.
I understand what it does.. My question however is not HOW does it do but why?
Logically speaking it should be compatible with the programming features like polymorphism. Why this class was made to ignore it?
回答1:
Your class basically contains two properties with the same name. So if you try to deserialize some JSON which contains that property name, there's no way of knowing which property to set.
Likewise when serializing an object of that type, you've got two values which need to be serialized using the same property name - what would you expect the JSON to look like?
Fundamentally, a type with two properties of the same name is incompatible with serialization of a plain name/value pair format. (A more advanced serialization mechanism which could specify which property was associated with which declaring class would cope, but JSON doesn't do that.)
来源:https://stackoverflow.com/questions/13705158/why-json-serializer-is-not-compliant-with-polymorphism