我在使用 VS2012 中的“将 XML 粘贴为类”功能以使用 Web API 正确反序列化来自 Rest 调用的 XML 结果时遇到问题。
调用的 XML 响应如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SCResponse>
<AccountId>86</AccountId>
<Administrator>false</Administrator>
<Email>6z@z.com</Email>
<FirstName>6z@z.com</FirstName>
<Label>false</Label>
<LastName>6z@z.com</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;
}
并检查 Account 对象的字段——全部为 null 或默认为初始化值。
在我的 Global.asax.cs Application_Start 方法中,我正在注册 XML 序列化器:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;