Search code examples
.netdictionarydatacontractserializer

How to serialize a Dictionary<string, List<string>> using DataContractSerializer?


When I try to have this class serialized I get a CommunicationException. Do I need to use any specific CollectionDataContract markup to get this working?

[DataContract()]
public class MyClass
{
  [DataMember()]
  public Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
}

Solution

  • This should just work (see examples below). What's the full exception which you get?

    public class StackOverflow_6966835
    {
        [DataContract()]
        public class MyClass
        {
            [DataMember()]
            public Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
        }
        [ServiceContract]
        public interface ITest
        {
            [OperationContract]
            MyClass GetMyClass();
        }
        public class Service : ITest
        {
            public MyClass GetMyClass()
            {
                return new MyClass
                {
                    dictionary = new Dictionary<string, List<string>>
                    {
                        { "one", "uno un eins".Split().ToList() },
                        { "two", "dos deux zwei".Split().ToList() },
                        { "three", "tres trois drei".Split().ToList() }
                    }
                };
            }
        }
        public static void Test()
        {
            Console.WriteLine("Stand-alone serialization");
            MemoryStream ms = new MemoryStream();
            MyClass c = new Service().GetMyClass();
            DataContractSerializer dcs = new DataContractSerializer(typeof(MyClass));
            dcs.WriteObject(ms, c);
            Console.WriteLine("Serialized: {0}", Encoding.UTF8.GetString(ms.ToArray()));
    
            Console.WriteLine();
            Console.WriteLine("Now using in a service");
    
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
            host.Open();
            Console.WriteLine("Host opened");
    
            ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();
    
            Console.WriteLine(proxy.GetMyClass());
    
            ((IClientChannel)proxy).Close();
            factory.Close();
    
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
    }