DataContractJsonSerializer:基于JSON属性反序列化为不同的类型

时间:2015-06-24 08:54:11

标签: c# json serialization

我正在使用DataContractJsonSerializer从Web服务中反序列化JSON。

[{"id":2947,"type":"PdfDocument","name":"test.pdf"},
 {"id":2945,"type":"ImageDocument","name":"test.jpg", "color": "green"}]

根据其类型,JSON实体可以具有不同的属性(例如颜色)。目前我使用单个模型Document进行反序列化,使用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";    
    }
}

但是,这对我来说感觉“很臭”。是否可以根据Document的JSON值自动反序列化为type的子类?

0 个答案:

没有答案