我試圖反序列化API響應中返回的一些XML,但反序列化後,對象中的所有值都是NULL。C#:反序列化XML後的對象值爲空
下面是我正在嘗試反序列化的響應XML。
<?xml version="1.0" encoding="utf-8"?>
<ctatt>
<tmst>20160609 11:50:03</tmst>
<errCd>0</errCd>
<errNm />
<eta>
<staId>41300</staId>
<stpId>30252</stpId>
<staNm>Loyola</staNm>
<stpDe>Service toward 95th/Dan Ryan</stpDe>
<rn>803</rn>
<rt>Red</rt>
<destSt>30089</destSt>
<destNm>95th/Dan Ryan</destNm>
<trDr>5</trDr>
<prdt>20160609 11:48:45</prdt>
<arrT>20160609 11:51:45</arrT>
<isApp>0</isApp>
<isSch>0</isSch>
<isDly>0</isDly>
<isFlt>0</isFlt>
<flags />
<lat>42.01906</lat>
<lon>-87.67289</lon>
<heading>130</heading>
</eta>
</ctatt>
這裏是我的類:
[Serializable, XmlRoot("ctatt")]
public class trainData
{
[XmlElement(ElementName ="tmst")]
public string timeStamp { get; set; }
[XmlElement(ElementName = "errCd")]
public byte errorCode { get; set; }
[XmlElement(ElementName = "staId")]
public ushort stationId { get; set; }
[XmlElement(ElementName = "stpId")]
public ushort stopId { get; set; }
[XmlElement(ElementName = "staNm")]
public string stationName { get; set; }
[XmlElement(ElementName = "stpDe")]
public string stopDesc { get; set; }
[XmlElement(ElementName = "rn")]
public ushort runNum { get; set; }
[XmlElement(ElementName = "rt")]
public string routeName { get; set; }
[XmlElement(ElementName = "destSt")]
public ushort destStation { get; set; }
[XmlElement(ElementName = "destNm")]
public string destName { get; set; }
[XmlElement(ElementName = "trDr")]
public byte trainDir { get; set; }
[XmlElement(ElementName = "prdt")]
public string prdTime {get; set;}
[XmlElement(ElementName = "arrT")]
public string arrTime { get; set; }
[XmlElement(ElementName = "isApp")]
public ushort isApp { get; set; }
[XmlElement(ElementName = "isSch")]
public ushort isSch { get; set; }
[XmlElement(ElementName = "isDly")]
public ushort isDly { get; set; }
[XmlElement(ElementName = "isFlt")]
public ushort isFlt { get; set; }
[XmlElement(ElementName = "flags")]
public string flags { get; set; }
[XmlElement(ElementName = "lat")]
public double lat { get; set; }
[XmlElement(ElementName = "lon")]
public double lon { get; set; }
[XmlElement(ElementName = "heading")]
public ushort heading { get; set; }
}
這裏是我使用的反序列化的代碼:
var response = await client.GetAsync(urlParameters);
if (response.IsSuccessStatusCode)
{
var xml = await response.Content.ReadAsStringAsync();
XmlSerializer deserializer = new XmlSerializer(typeof(trainData));
using (StringReader reader = new StringReader(xml))
{
using (XmlReader xr = XmlReader.Create(reader))
{
trainData result = (trainData)deserializer.Deserialize(xr);
Console.WriteLine("Station Name: {0}\nRoute Name: {1}\nArrival Time: {2}", result.stationName, result.routeName, result.arrTime);
}
}
}
else
{
Console.WriteLine("There was an error!");
}
任何建議,將不勝感激...
你還應該包括你正在獲取的堆棧跟蹤。 –
'trainData'需要一個'eta'類型作爲屬性。這些嵌套在'eta'中的元素不能在'trainData'上反序列化。 – Crowcoder