C# DataContractJsonSerializer:基于JSON属性反序列化为不同类型
我正在使用DataContractJsonSerializer从Web服务反序列化JSONC# DataContractJsonSerializer:基于JSON属性反序列化为不同类型,c#,json,serialization,C#,Json,Serialization,我正在使用DataContractJsonSerializer从Web服务反序列化JSON [{"id":2947,"type":"PdfDocument","name":"test.pdf"}, {"id":2945,"type":"ImageDocument","name":"test.jpg", "color": "green"}] 根据其类型,JSON实体可以具有不同的属性,例如颜色。目前,我使用一个模型文档进行反序列化,并使用PagedCollectionViews过滤需要在UI中
[{"id":2947,"type":"PdfDocument","name":"test.pdf"},
{"id":2945,"type":"ImageDocument","name":"test.jpg", "color": "green"}]
根据其类型,JSON实体可以具有不同的属性,例如颜色。目前,我使用一个模型文档进行反序列化,并使用PagedCollectionViews过滤需要在UI中显示的内容
public class Document : EntityBase
{
private string name;
private string type;
private string color;
public Document()
{
}
[DataMember(Name = "name")]
public string Name
{
get
{
return this.name;
}
set
{
if (this.name != value)
{
this.name = value;
this.OnPropertyChanged("Name");
}
}
}
[DataMember(Name = "type")]
public string Type
{
get
{
return this.type;
}
set
{
if (this.type != value)
{
this.type = value;
this.OnPropertyChanged("Type");
}
}
}
[DataMember(Name = "color")]
public string Color
{
get
{
return this.color;
}
set
{
if (this.color != value)
{
this.color= value;
this.OnPropertyChanged("Color");
}
}
}
}
public class DocumentsViewModel : ViewModelBase
{
public ObservableCollection<Document> Documents { get; set; }
public PagedCollectionView ImageDocuments;
public PrintProjectDetailsViewModel()
{
this.Documents = new ObservableCollection<Document>();
this.ImageDocuments = new PagedCollectionView(Documents);
this.ImageDocuments.Filter = (o) => ((Document)o).Type == "ImageDocument";
}
}
然而,我觉得这很难闻。是否可以根据类型的JSON值自动反序列化为文档的子类?我认为没有办法-对于框架来说,.NET对象的类型字段只是一个常规字符串字段。您可以尝试编写函数来隐藏这一点,但最终,它将始终是一个进行区分的开关。首先,您最好切换到Json.NET,它是ASP.NET Web API和下一个MVC使用的首选Json序列化程序。DataContractSerializer很古老,在Json格式标准化之前创建,存在各种问题,例如日期格式。其次,基于子属性字段的反序列化也不是干净的。您可以使用JSon.Net反序列化到动态对象,然后使用字段的value@PanagiotisKanavos我接受这个答案。