0

i'm using this class

public class Branch
{
    public string Name { get; set; }
    public User Manager { get; set; }
    public User Secretary { get; set; }

    public Dictionary<string, User> Broker;
    public Dictionary<string, Apartment> Apartments;

    public Branch()
    {}

    public Branch(Branch other)
    {
        Name = other.Name;
        Manager = other.Manager;
        Secretary = other.Secretary;
        Broker = other.Broker;
        Apartments = other.Apartments;
    }
}

trying to run this line : Dict2XML.Save_Branch2XML(Branchs);

through this method:

static public void Save_Branch2XML(Dictionary<string, Branch> D)
{

    //List<KeyValuePair<string, User>> DictionList = D.ToList();
    List<Branch> DictionList = D.Select(p  => new Branch(p.Value)).ToList<Branch>();
    XmlSerializer Serializer = new XmlSerializer(DictionList.GetType());
    TextWriter writer = new StreamWriter(@"C:\Users\tzach_000\Documents\Visual Studio 2013\Projects\RealEstate\RealEstate\DB\XMLBranch.xml");
    Serializer.Serialize(writer, DictionList);
    writer.Close();
}

and the program collapse when it gets to the XmlSerializer line in save_branch2xml method.

derekerdmann
  • 17,696
  • 11
  • 76
  • 110
  • 1
    What do you mean by "the program collapse"? I suspect you mean an exception is thrown - in which case you should give the details of the exception. – Jon Skeet Dec 26 '13 at 21:13

2 Answers2

1

The XmlSerializer doesn't support dictionaries, I don't think it changed for all these years. There are multiple workarounds, two of them could be recommended.

First, change the internal data structure for one that is serializable. A list of pairs would do.

Second, use the DataContractSerializer rather than the xml serializer. The data contract serializer supports serialization of dictionaries.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
0

See this thread

Serialize Class containing Dictionary member

You can use SerializableDictionary if you really want.

Community
  • 1
  • 1
h__
  • 761
  • 3
  • 12
  • 41