2011-11-12 60 views
0

我使用維基百科API查詢數據並希望將結果轉換爲字符串[]。使用Json.net轉換維基百科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

維基百科的API(使用JSON)假設你使用JSONP。你可以只完全從您的查詢字符串下降回調參數:

en.wikipedia.org/w/api.php?action=opensearch &搜索=測試&格式= 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(); 
    } 
}