mBrice1024
mBrice1024

Reputation: 838

Issue serializing a class that references itself as a property

Say this my class that is generated via recursive call:

public class Level
{
    public string Name { get; set; }
    public string Value { get; set; }
    public List<Level> NextLevel { get; set; }
    public Level()
    {
        NextLevel = new List<Level>();
    }
}

However when I try to serialize this to xml I get this error:

The type System.Collections.Generic.List`1[[....ResponseModel+Level, Testing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context.

I've tried Json serialization and it's fine.

I assume it's having an issue with the NextLevel property. Is there a special attribute needed here?

I have not found much info about this.

Upvotes: 1

Views: 223

Answers (1)

Visual Vincent
Visual Vincent

Reputation: 18310

To serialize lists/arrays using XML Serialization you would generally have to apply the XmlArray and XmlArrayItem attributes to your property in order to specify that it should serialize it as a nested sequence of XML elements:

[XmlArray("NextLevel")]
[XmlArrayItem("Level")]
public List<Level> NextLevel { get; set; }

Upvotes: 1

Related Questions