1

I've been trying to serialize a class (see below) which inherits from List<int> and has fields that provide extra information.

Originally, I had been using XmlSerializer, however I was having issues there as well.

According to this post it is by design with XmlSerializer does not serialize fields but DataContractSerializer should work.

Any suggestions would be greatly appreciated!

[CollectionDataContract]
public class Group : List<int>
{
    [DataMember]
    public string Key { get; set; }
}

static void Main()
{
    Group test = new Group { Key = "Test key" };
    test.Add(60);

    DataContractSerializer serializer = new DataContractSerializer(typeof(Group));
    MemoryStream stream = new MemoryStream();

    serializer.WriteObject(stream, test);

    stream.Position = 0;
    test = serializer.ReadObject(stream) as Group;
    Console.WriteLine("{0}: {1}", test.Key ?? "No luck", test[0]);
}

Thanks, Noah

Community
  • 1
  • 1
noah
  • 13
  • 2

2 Answers2

0

This is the expected behavior. When deriving from a collection only base class will be serialized :) I would suggest creating a base wrapper class.

[DataContract]
class SuperWrapper {
    private List<int> _myList;
    private string _name;

    [DataMember]
    public List<int> Items { get { return _items; } set { _items = value; } }

    [DataMember]
    public string Name { get { return _name; } set { _name = value; } }
}
Hasan Emrah Süngü
  • 2,990
  • 1
  • 9
  • 27
  • Unfortunately I need to expose the object in this way. I think I'll have to implement a wrapper to provide the interface I needed, then part of serialization will have to be to turn the object into something like you mentioned. Thanks! – noah Oct 27 '16 at 04:15
0

You need to create a DTO which will contain all objects or properties

[DataContract]
class ResponseDTO 
{

    [DataMember]
    public List<int> ListData{ get ;set; }

    [DataMember]
    public string Key{  get ;set; }
}
Danh
  • 5,455
  • 7
  • 26
  • 41
Ghost Developer
  • 915
  • 1
  • 7
  • 15