Ziv Weissman
Ziv Weissman

Reputation: 4536

Json serialize dictionary inside a dictionary

I have the following problem-

I'm trying to serialize a class which contains a class that has an additional dictionary.

The structure is simplified to the following:

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; }
}

I'm trying to use it in API, and return a serialized version of GroupVM. For some reason, I'm getting nothing in the Attributes Dictionary (inside ClusterVM class).

If I change it to List, it works fine.

Code Sample

Upvotes: 0

Views: 139

Answers (1)

Nkosi
Nkosi

Reputation: 247471

According to the sample code the Attributes property was not public

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

It could not get serialized because the serializer was unaware of its presence. Make the property public and it should get serialized.

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);
    }
}

Upvotes: 1

Related Questions