BrunoLM
BrunoLM

Reputation: 100361

How to serialize a class with a list of custom objects?

I have two classes:

namespace Something
{
    [Serializable]
    public class Spec
    {
        public string Name { get; set; }

        [XmlArray]
        public List<Value> Values { get; set; }
    }

    [Serializable]
    public class Value
    {
        public string Name { get; set; }

        public short StartPosition { get; set; }

        public short EndPosition { get; set; }

        public Value(string name, short startPosition, short endPosition)
        {
            Name = name;
            StartPosition = startPosition;
            EndPosition = endPosition;
        }
    }
}

When I try to serialize

var spec = new Spec();
spec.Name = "test";
spec.Values = new List<Value> { new Value("testing", 0, 2) };

var xmls = new XmlSerializer(spec.GetType());    
xmls.Serialize(Console.Out, spec);

I get an error:

InvalidOperationException

There was an error reflecting type 'Something.Spec'

Using a list of string I don't have any problems. Am I missing some attribute?

Upvotes: 4

Views: 13514

Answers (2)

Matthew Abbott
Matthew Abbott

Reputation: 61599

Could it be that your Value type doesn't have a constructor that can be used to create an instance when deserialising?

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039170

The Value class needs to have a default constructor if you want it to be serializable. Example:

public class Value
{
    public string Name { get; set; }
    public short StartPosition { get; set; }
    public short EndPosition { get; set; }
}

Also not that you don't need the [Serializable] attribute for XML serialization and it is completely ignored by the XmlSerializer class.

Upvotes: 7

Related Questions