当然,只需安装 Microsoft.AspNet.WebApi.Client 包 - http://nuget.org/packages/Microsoft.AspNet.WebApi.Client/4.0.20710.0
现在您可以调用外部服务并直接读入您的对象:
var client = new HttpClient();
var response = await client.GetAsync("http://thegamesdb.net/api/GetGamesList.php?name=x-men");
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsAsync<Data>();
foreach (var game in data.Game)
{
Console.WriteLine("{0}\t{1};\t{2}", game.Id, game.GameTitle, game.Platform);
}
}
编辑:
鉴于 XML 具有非标准的集合格式,请执行以下操作:
[XmlRoot("Data")]
public class Data
{
[XmlElement("Game")]
public List<Game> Games { get; set; }
}
[XmlType("Game")]
public class Game
{
public int id { get; set; }
public string GameTitle { get; set; }
public string ReleaseDate { get; set; }
public string Platform { get; set; }
}
和:
var client = new HttpClient();
var response = await client.GetAsync("http://thegamesdb.net/api/GetGamesList.php?name=x-men");
if (response.IsSuccessStatusCode)
{
var games = await response.Content.ReadAsAsync<Data>(new HashSet<MediaTypeFormatter>() { new XmlMediaTypeFormatter {UseXmlSerializer = true} });
foreach (var game in games.Games)
{
Console.WriteLine("{0}\t{1};\t{2}", game.id, game.GameTitle, game.Platform);
}
}
我们需要提示XmlSerializer
如何处理真正以属性形式发送给您的数组。此外,它们的日期无效,因此您应该将其保存为字符串(或在 setter 中解析)。
另外,由于我们使用XmlSerializer
not DataContractSerializer
,您不能使用IEnumerable
,它必须是List<T>
。