使用“将XML粘贴为类”来反序列化Web API休息响应

时间:2013-04-26 13:27:08

标签: c# asp.net-mvc asp.net-web-api xml-serialization deserialization

我在使用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 Serializer:

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

1 个答案:

答案 0 :(得分:0)

处理此问题的一种更简单的方法可能是使用RestSharp library,它将为您执行所有反序列化。这将简化您的调用,您不需要模型上的XML属性。

在这里查看使用RestSharp进行异步调用的一个很好的例子:

How should I implement ExecuteAsync with RestSharp on Windows Phone 7?

希望这有帮助。