我在使用VS2012中的'將XML粘貼爲類'功能來正確反序列化來自使用Web API的Rest調用的XML結果時遇到問題。使用'將XML粘貼爲類'來反序列化Web API休息響應
從調用的XML響應如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SCResponse>
<AccountId>86</AccountId>
<Administrator>false</Administrator>
<Email>[email protected]</Email>
<FirstName>[email protected]</FirstName>
<Label>false</Label>
<LastName>[email protected]</LastName>
<link href="https://cnn.com" rel="news" title="News"/>
</SCResponse>
我複製此XML和使用的方便的新功能,粘貼此XML作爲類:
namespace Models.account.response
{
[XmlRoot(ElementName = "SCResponse")] // I added this so I could name the object Account
[DataContract(Name = "SCResponse", Namespace = "")] // I added this as the namespace was causing me problems
public partial class Account
{
public byte AccountId { get; set; }
public bool Administrator { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public bool Label { get; set; }
public string LastName { get; set; }
[XmlElement("link")]
public SCResponseLink[] Link { get; set; }
}
[XmlType(AnonymousType = true)]
public partial class SCResponseLink
{
private string hrefField;
private string relField;
private string titleField;
[XmlAttribute)]
public string href { get; set; }
XmlAttribute]
public string rel { get; set; }
[XmlAttribute]
public string title { get; set; }
}
}
}
我稱之爲REST端點像這樣:
string path = String.Format("account/{0}", id);
HttpResponseMessage response = client.GetAsync(path).Result; // Blocking call!
if (response.IsSuccessStatusCode)
{
// Parse the response body. Blocking!
account = response.Content.ReadAsAsync<Models.account.response.Account>().Result;
}
並檢查帳戶對象的所有字段 - 全部爲空或默認值克到初始化值。
在我的Global.asax.cs Application_Start方法中,我註冊XML序列:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
當您使用[DataContract]時,您是否需要爲每個屬性添加[DataMember]屬性... – 2013-04-26 13:48:24