I am having an API XML response, that looks like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<artists itemsPerPage="30">
<artist id="a0d9633b">
<url>http://www.somesite.com/3df8daf.html</url>
</artist>
</artists>
For deserializing it I use classes:
[SerializableAttribute]
[XmlTypeAttribute(TypeName = "result")]
public abstract class Result
{
private int _itemsPerPage;
[XmlAttributeAttribute(AttributeName = "itemsPerPage")]
public int ItemsPerPage
{
get { return this._itemsPerPage; }
set { this._itemsPerPage = value; }
}
}
[SerializableAttribute]
[XmlTypeAttribute(TypeName = "artists")]
[XmlRootAttribute(ElementName = "artists")]
public class Artists : Result, IEnumerable<Artist>
{
private List<Artist> _list;
[XmlElementAttribute(ElementName = "artist")]
public List<Artist> List
{
get { return this._list; }
set { this._list = value; }
}
public Artists()
{
_list = new List<Artist>();
}
public void Add(Artist item)
{
_list.Add(item);
}
IEnumerator IEnumerable.GetEnumerator() { return _list.GetEnumerator(); }
public IEnumerator<Artist> GetEnumerator()
{
foreach (Artist artist in _list)
yield return artist;
}
}
[SerializableAttribute]
[XmlTypeAttribute(TypeName = "artist")]
[XmlRootAttribute(ElementName = "artist")]
public class Artist
{
private string _mbid;
private string _url;
[XmlAttributeAttribute(AttributeName = "mbid")]
public string MBID
{
get { return this._mbid; }
set { this._mbid = value; }
}
[XmlElementAttribute(ElementName = "url")]
public string Url
{
get { return this._url; }
set { this._url = value; }
}
public Artist() { }
}
And this is how I do deserialization:
XmlSerializer serializer = new XmlSerializer(typeof(Artists));
Artists result = (Artists)serializer.Deserialize(new StreamReader("artists.xml"));
So, the problem is, that when I do deserialization, ItemsPerPage
doesn't have a needed (30) value (it has default 0). However, if I remove IEnumerable<Artist>
interface and deserialize Artists, the value will appear. I can remove interface and leaves Artists
with only IEnumerator<Artist> GetEnumerator()
method, so everything will be fine, Artists
still can be foreach'ed, but will no longer be IEnumerable<Artist>
. Which is not what I want.
The problem is not in base class, because I can transfer property ItemsPerPage
to Artists
class, and deserialization result will be the same.
Any ideas how I can deserialize ItemsPerPage value with Artists
still being IEnumerable<Artist>
?