gpt4 book ai didi

c# - 使用 'Paste XML as Classes' 反序列化 Web API 剩余响应

转载 作者:太空宇宙 更新时间:2023-11-03 16:14:13 25 4
gpt4 key购买 nike

我无法使用 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 对象的字段——全部为空或默认为初始化值。

在我的 Global.asax.cs Application_Start 方法中,我正在注册 XML 序列化程序:

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

最佳答案

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

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

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

希望这对您有所帮助。

关于c# - 使用 'Paste XML as Classes' 反序列化 Web API 剩余响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16237665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com