2017-05-14 43 views
0

我有以下問題Json序列化字典裏面的字典

我想序列化一個類,其中包含一個類有一個額外的字典。

結構簡化爲以下幾點:

public class GroupVM 
{ 
    public GroupVM() 
    { 
     this.Clusters = new Dictionary<int, ClusterVM>(); 
    } 

    public Dictionary<int,ClusterVM> Clusters { get; set; } 
} 

public class ClusterVM 
{ 
    public ClusterVM() 
    { 
     this.Attributes = new Dictionary<Guid, AttributeVM>(); 
    } 
    Dictionary<Guid,AttributeVM> Attributes { get; set; } 

    public void AddAttribute(Guid guid, string name) 
    { 
     AttributeVM attrVM = new AttributeVM(); 
     attrVM.Name = name; 
     attrVM.Guid = guid; 
     this.Attributes.Add(guid,attrVM); 
    } 
} 

public class AttributeVM 
{ 
    public Guid Guid { get; set; } 
    public string Name { get; set; } 
} 

我試圖使用它的API,並返回GroupVM的序列化版本。出於某種原因,我在「屬性字典」(ClusterVM類中)中沒有任何內容。

如果我改變它列出,它工作正常。

Code Sample

回答

1

根據示例代碼Attributes財產不公開

Dictionary<Guid,AttributeVM> Attributes { get; set; } 

它無法得到序列化,因爲串行不知道它的存在。公開財產,它應該被序列化。

public class ClusterVM { 
    public ClusterVM() { 
     this.Attributes = new Dictionary<Guid, AttributeVM>(); 
    } 

    public IDictionary<Guid,AttributeVM> Attributes { get; set; } 

    public void AddAttribute(Guid guid, string name) { 
     AttributeVM attrVM = new AttributeVM(); 
     attrVM.Name = name; 
     attrVM.Guid = guid; 
     this.Attributes.Add(guid,attrVM); 
    } 
}