我必须从XML(greatschool API)反序列化到Class Domain。
网址: http://www.greatschools.org/api/docs/nearbySchools.page
XML:
<schools>
<school>
<gsId>936</gsId>
<name>Centerville Elementary</name>
<type>public</type>
<gradeRange>K-6</gradeRange>
...
</schools>
我为转换
创建了这样的DOMain[Serializable()]
[System.Xml.Serialization.XmlRoot("schools")]
public class SchoolResponse
{
[XmlArray("schools")]
[XmlArrayItem("school", typeof(School))]
public School[] school { get; set; }
}
[Serializable()]
public class School
{
[System.Xml.Serialization.XmlElement("gsId")]
public string GSId { get; set; }
[System.Xml.Serialization.XmlElement("name")]
public string Name { get; set; }
....
}
通话方式:
var url = new Uri(this.BaseUri, request.ToUri());
return Internal.Http.Get(url,"XML").As<SchoolResponse>();
...
public virtual T As<T>() where T : class
{
T output = null;
using (var reader = GetStreamReader(this.RequestUri))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
output = (T)serializer.Deserialize(reader);
}
return output;
}
返回null。请帮忙
答案 0 :(得分:1)
问题在于school
数组属性。试试这个
[Serializable()]
[System.Xml.Serialization.XmlRoot("schools")]
public class SchoolResponse
{
[XmlElement("school")]
public School[] school { get; set; }
}
通常,C#XML喜欢有数组名称元素,然后是每个数组值的元素。通过在数组上使用[XmlElement]
,不会生成外部元素。
答案 1 :(得分:0)
我认为 - 学校类型的有效值为:&#34; public&#34;,&#34; charter&#34;,&#34; private&#34;或任何以连字符分隔的组合,例如& #34;公共包机&#34; 我认为最好的变体是声明这样的枚举类型:
public enum SchoolType
{
[XmlEnum("public")]
Public,
[XmlEnum("charter")]
Charter,
[XmlEnum("private")]
Private,
[XmlEnum("public-charter")]
PublicCharter,
[XmlEnum("public-private")]
PublicPrivate,
[XmlEnum("private-charter")]
PrivateCharter,
[XmlEnum("public-charter-private")]
PublicCharterPrivate
}
然后你的类定义将如下所示:
[Serializable]
public class School
{
[XmlElement("gsId")] //Custom property name
public string GSId { get; set; } //The same property name
public string name { get; set; }
public string type { get; set; }
public string gradeRange { get; set; }
[XmlElement("schoolType")] //Enum declaration
public SchoolType SchoolType { get; set; }
}
但你也应检查所有变种