Search code examples
c#serializationdatacontractserializer

Custom serialization using DataContractSerializer


I am having a look into using the DataContractSerializer and I'm having trouble getting the right output format. The DataContractSerializer serializes the following class

[DataContract(Name = "response")]
public class MyCollection<T> 
{
    [DataMember]
    public List<T> entry { get; set; }
    [DataMember]
    public int index { get; set; }
}

Into

<response><entry><T1>object1</T1><T2>object2</T2></entry><index></index></response>

But what I want is

<response><entry><T1>object1</T1></entry><entry><T2>object2</T2></entry><index></index></response>

How do I do this with the DataContractSerializer? But also maintain the first output for DataContractJsonSerializer?


Solution

  • If you are writing xml, I wonder whether xml serializer wouldn't be a better choice (it has more granular control over the names, etc).

    The problem, though, is that XmlSerializer isn't always the biggest fan of generics...

    Additionally - having tried a few options involving [XmlArray] / [XmlArrayItem] etc... it looks very hard to get it to the format you want... plus it isn't easy to guess what you mean by the T1 / T2 - but the following may come close:

    [XmlRoot("response")]
    public class MyResponse : MyCollection<int> { }
    
    [DataContract(Name = "response")]
    public class MyCollection<T>
    {
        [DataMember]
        [XmlElement("entry")]
        public List<T> entry { get; set; }
        [DataMember]
        public int index { get; set; }
    }
    

    This has both XmlSerializer and DataContractSerializer attributes, but I had to lose the generics in the type we use for the response (hence the "closed" MyResponse type)