Custom serialization using DataContractSerializer

I am looking at using a DataContractSerializer and I'm having trouble getting the correct output format. 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; }
}

IN

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

But I want

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

How to do this with a DataContractSerializer? But also save the first result for the DataContractJsonSerializer?

+3
source share
2 answers

If you write xml, I wonder if the XML serializer would be a more efficient choice (it has more detailed control over names, etc.).

The problem is that it is XmlSerializernot always the biggest fan of generics ...

, [XmlArray]/[XmlArrayItem] .., ... - , T1/T2 - :

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

XmlSerializer DataContractSerializer, , (, "" MyResponse)

+2

, DataContractSerializer xml.

http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/

MS : ' DataContractAttribute , ISerializable SerializableAttribute. , . '

PS: , , .

,

+4

Source: https://habr.com/ru/post/1710244/


All Articles