【问题标题】:Json serialize dictionary inside a dictionary字典中的Json序列化字典
【发布时间】:2017-05-14 11:50:24
【问题描述】:

我有以下问题-

我正在尝试序列化一个包含具有附加字典的类的类。

结构简化为:

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 类中)中什么也没有。

如果我将其更改为 List,它可以正常工作。

Code Sample

【问题讨论】:

    标签: c# json serialization


    【解决方案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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多