【问题标题】:Using 'Paste XML as Classes' to deserialize a Web API rest response使用“将 XML 粘贴为类”反序列化 Web API 休息响应
【发布时间】:2013-04-20 16:48:19
【问题描述】:

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

【问题讨论】:

  • 在使用[DataContract]时是否需要在每个属性中添加[DataMember]属性...

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


【解决方案1】:

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

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

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多