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 message:

InvalidOperationException

An error occurred reflecting the type "Something.Spec"

Using the string list I have no problem. Did I miss some attribute?

+4
source share
2 answers

The Value class must 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; } } 

In addition, you do not need the [Serializable] attribute to serialize XML, and it is completely ignored by the XmlSerializer class.

+6
source

Could it be that your Value type does not have a constructor that can be used to instantiate during deserialization?

0
source

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


All Articles