JSON使用多态对象数组进行反序列化

我遇到了涉及多态对象数组的JSON反序列化问题。 我已经尝试了这里和这里记录的序列化解决方案,这些解决方案非常适合序列化,但是它们都在反序列化方面有所作为。

我的class级结构如下:

IDable

[DataContract(IsReference=true)] public abstract class IDable { [DataMember] public T ID { get; set; } } 

观察组

 [DataContract(IsReference=true)] [KnownType(typeof(DescriptiveObservation))] [KnownType(typeof(NoteObservation))] [KnownType(typeof(NumericObservation))] [KnownType(typeof(ScoredObservation))] public class ObservationGroup : IDable { [DataMember] public string Title { get; set; } [DataMember] public List Observations { get; set; } [OnDeserializing] void OnDeserializing(StreamingContext context) { init(); } public ObservationGroup() { init(); } private void init() { Observations = new List(); ObservationRecords = new List(); } } 

DescriptiveObservation

 [DataContract(IsReference = true)] public class DescriptiveObservation : Observation { protected override ObservationType GetObservationType() { return ObservationType.Descriptive; } } 

NoteObservation

 [DataContract(IsReference = true)] public class NoteObservation : Observation { protected override ObservationType GetObservationType() { return ObservationType.Note; } } 

NumericObservation

 [DataContract(IsReference = true)] public class NumericObservation : Observation { [DataMember] public double ConstraintMaximum { get; set; } [DataMember] public double ConstraintMinimum { get; set; } [DataMember] public int PrecisionMaximum { get; set; } [DataMember] public int PrecisionMinimum { get; set; } [DataMember] public string UnitType { get; set; } protected override ObservationType GetObservationType() { return ObservationType.Numeric; } } 

ScoredObservation

 [DataContract(IsReference = true)] public class ScoredObservation : Observation { [DataMember] public int Value { get; set; } protected override ObservationType GetObservationType() { return ObservationType.Scored; } } 

我使用内置的JavaScriptSerializer或Newtonsoft JSON库是公正的。

序列化代码

 var settings = new Newtonsoft.Json.JsonSerializerSettings(); settings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects; Newtonsoft.Json.JsonConvert.SerializeObject(AnInitializedScoresheet, Newtonsoft.Json.Formatting.None, settings); 

反序列化代码

 return Newtonsoft.Json.JsonConvert.DeserializeObject(returnedStringFromClient, typeof(Scoresheet)); //Scoresheet contains a list of observationgroups 

我得到的错误是

“无法创建ProjectXCommon.DataStores.Observation类型的实例.Type是一个接口或抽象类,无法立即显示。”

任何帮助将非常感激!

您没有在反序列化时添加任何设置。 您需要将TypeNameHandling设置为ObjectAll来应用设置。

像这样:

 JsonConvert.DeserializeObject( returnedStringFromClient, typeof(Scoresheet), new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }); 

文档: TypeNameHandling设置