解析ASP.NET MVC中的JSON值时出错?

我正在尝试使用StackOverflow的搜索API来搜索问题。

我正在使用此操作来执行解析:

public ActionResult StackExchange(string sq) { string url = "http://api.stackoverflow.com/1.1/search?intitle=" + sq + "&order=desc"; var client = new WebClient(); var response = client.DownloadString(new Uri(url)); JObject o = JObject.Parse(response);// ERROR int total = (int)o["total"]; return View(total); } 

这是我要解析的JSON url:

http://api.stackoverflow.com/1.1/search?intitle=asp.net%20custom%20404&order=desc

我想提取以下数据:

 `"total": 3` , `"question_timeline_url": "/questions/10868557/timeline",` `"title": "Asp.net custom 404 not working using Intelligencia rewriter"` 

给出错误为: Newtonsoft.Json.JsonReaderException:解析值时遇到意外的字符:。 路径”,第0行,第0位。

什么是例外的原因? 我之前使用了相同的方法并且工作正常。

请建议。

尝试以下方法。

使用NuGet并引用JSON.NET包。 我知道你已经这样做了。

撰写请求并获得响应。

 string url = "http://api.stackoverflow.com/1.1/search?intitle=test&order=desc"; var request = (HttpWebRequest) WebRequest.Create(url); var response = request.GetResponse(); 

您从Stack Exchange API收到的响应是gzip压缩的! 首先需要解压缩它才能读取JSON响应。 这就是您收到例外的原因。

让我们创建一个方法来做到这一点。 .NET为此提供了方便的GZipStream类型。

 private string ExtractJsonResponse(WebResponse response) { string json; using (var outStream = new MemoryStream()) using (var zipStream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)) { zipStream.CopyTo(outStream); outStream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(outStream, Encoding.UTF8)) { json = reader.ReadToEnd(); } } return json; } 

现在,您可以从响应中提取JSON数据。

 var json = ExtractJsonResponse(response); 

现在您可以解析返回的数据。

 JObject o = JObject.Parse(json); int total = (int)o["total"]; 

去年我写了一篇关于如何使用Stack Exchange API 1.1版的博客文章。

http://cgeers.com/2011/10/02/stack-exchange-api/

PS:我建议你使用今年早些时候发布的API 2.0版本。

https://api.stackexchange.com/docs

我的第一个猜测,因为JsonReader在第0行给出了一个exception,位置0是某些东西搞乱了编码。 由于上面的请求在chrome开发人员工具中显示以下Content-Type标头

 Content-Type:application/json; charset=utf-8 

您可以尝试通过WebClient的Encoding属性将WebClient使用的编码设置为utf-8。