14

显然HttpClient是提出 HTTP 请求的新推荐方式,因此我尝试使用它向 Delicious API 发出请求,该 API 返回 XML 响应。这是我所拥有的:

internal class Program
{
    private static void Main(string[] args)
    {
        var credentials = new NetworkCredential("username", "password");
        var handler = new HttpClientHandler { Credentials = credentials};
        var client = new HttpClient(handler);

        var suggest = new Uri("https://api.del.icio.us/v1/posts/suggest");

        var suggestions =
            client.GetAsync(suggest.AddQueryParams("url", "https://yahoo.com"))
                .ContinueWith(t => t.Result.Content.ReadAsAsync<DeliciousSuggest>())
                .Unwrap()
                .Result;



        Console.ReadLine();
    }
}

public class DeliciousSuggest
{
    public string[] Popular { get; set; }
    public string[] Recommended { get; set; }
    public string[] Network { get; set; }
}

ReadAsAsync但是,它会在位上引发异常,

附加信息:无法加载文件或程序集“Newtonsoft.Json,版本=4.5.0.0,Culture=neutral,PublicKeyToken=30ad4fe6b2a6aeed”或其依赖项之一。该系统找不到指定的文件。

也许我错过了一些集会,但这让我感到震惊。返回类型是 XML,而不是 JSON,但我仍然不太确定这个ReadAsAsync方法是如何工作的,或者我什至会如何指定它。

示例响应如下所示:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<suggest>
<popular>yahoo!</popular>
<popular>yahoo</popular>
<popular>web</popular>
<popular>tools</popular>
<popular>searchengines</popular>
<recommended>yahoo!</recommended>
<recommended>yahoo</recommended>
<recommended>web</recommended>
<network>for:Bernard</network>
<network>for:britta</network>
<network>for:deusx</network>
</suggest>

我怎样才能把它解析成一些可用的格式?

4

1 回答 1

19

“我怎样才能把它解析成一些可用的格式?”

    [XmlRoot("suggest")]
public class DeliciousSuggest {
    [XmlElement("popular")]
    public string[] Popular { get; set; }

    [XmlElement("recommended")]
    public string[] Recommended { get; set; }

    [XmlElement("network")]
    public string[] Network { get; set; }
}

并使用 XmlSerializer 反序列化。


您应该从 del.icio.us 读取响应作为字符串,然后您可以按如下方式对其进行反序列化:

var s = "this is the response from del"; 
var buffer = Encoding.UTF8.GetBytes(s); 
using (var stream = new MemoryStream(buffer)) { 
    var serializer = new XmlSerializer(typeof(DeliciousSuggest)); 
    var deliciousSuggest = (DeliciousSuggest)serializer.Deserialize(stream); 
    //then do whatever you want
}
于 2013-11-13T01:06:24.487 回答