0

我正在使用 wikipedia api 查询数据,并希望将结果转换为字符串 []。

查询“测试”

en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json&callback=spellcheck

在此处返回此结果:

spellcheck(["test",["Test cricket","Test","Testicle","Testudines","Testosterone","Test pilot","Test (assessment)","Testimonial match","Testimony","Testament (band)"]])

我可以使用 Json.net 删除或忽略标签“拼写检查”吗?如果我使用此代码转换响应,应用程序将崩溃:

Dictionary<string, string[]> dict = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(response); 
4

1 回答 1

4

Wikipedia 的 api(使用 JSON)假设您使用的是 JSONP。您可以从查询字符串中完全删除回调参数:

en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json

此外,您得到的结果可能无法转换为Dictionary<string, string[]>. 如果仔细观察,它实际上是一个数组,其中第一个对象是字符串(搜索词),第二个对象是字符串列表(结果)。

以下对我有用:

HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
    @"http://en.wikipedia.org/w/api.php?action=opensearch&search=test&format=json");

string[] searchResults = null;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    {
        JArray objects = JsonConvert.DeserializeObject<JArray>(reader.ReadToEnd());
        searchResults = objects[1].Select(j => j.Value<string>()).ToArray();
    }
}
于 2011-11-12T20:52:09.327 回答