簡體   English   中英

如何從GreatSchool API響應中反序列化

[英]how to deserialize from GreatSchool API Response

我必須反序列化從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;
            }

返回為空。 請幫忙

問題在於school數組屬性。 嘗試這個

[Serializable()]
[System.Xml.Serialization.XmlRoot("schools")]
public class SchoolResponse
{
   [XmlElement("school")]
   public School[] school { get; set; }
}

通常,喜歡C#XML的人都有一個數組名稱元素,然后每個數組值都有一個元素。 通過在數組上使用[XmlElement] ,不會生成外部元素。

如我所見-學校類型的有效值為:“ public”,“ charter”,“ private”或任何用連字符分隔的組合,例如“ public-charter”,我認為最適合您的是聲明枚舉類型,如下所示:

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; }
}

但您也應該檢查所有變體

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM