我想使用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垃圾 - 我猜是因为它是序列化的并且需要反序列化?
答案 0 :(得分:8)
我肯定会考虑使用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
答案 1 :(得分:3)
另请参阅Stacky StackApps .Net Client Library这是基于REST的API,它提供对stackoverflow系列网站的访问。
答案 2 :(得分:0)
不幸的是我在Mac上并且无法对您的代码进行测试。您可能需要检查页面和返回的响应流的字符编码。如果他们不匹配;它可能导致来自响应流的字符被错误地渲染,从而导致你看到的垃圾。