我想使用stackoverflow API的搜索方法返回基于搜索关键字的结果的json结构,然后在SearchResults div中显示这些结果(标题,描述和url).
我是C#的新手,我的第一次尝试是这样的:
protected void searchStockOverflow(string y) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle="+y); httpWebRequest.ContentType = "text/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{ \"intitle\": \"" + y + "\"}"; streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var responseText = streamReader.ReadToEnd(); SearchResults.InnerHtml += "<div style='border:1px solid blue;margin:5px;'>"; SearchResults.InnerHtml += responseText + "<br />"; SearchResults.InnerHtml += "</div><br style='clear:both;' />"; } }
问题是返回的东西看起来像dingbats垃圾 – 我猜是因为它是序列化的,需要反序列化?
解决方法
我肯定会说考虑使用REST客户端;但是,要查看问题…通常您希望手动将数据反序列化为JSON,然后通过UI代码运行该数据.例如:
static void SearchStackOverflow(string y) { var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.stackoverflow.com/1.1/search?intitle=" + Uri.EscapeDataString(y)); httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; httpWebRequest.Method = "GET"; var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); string responseText; using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { responseText = streamReader.ReadToEnd(); } var result = (SearchResult)new JavaScriptSerializer().Deserialize(responseText,typeof(SearchResult)); .... do something with result ... } class SearchResult { public List<Question> questions { get; set; } } class Question { public string title { get; set; } public int answer_count { get; set; } }
它使用System.Web.Extensions.dll中的JavaScriptSerializer