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

Man*_*lue 4 c# asp.net asp.net-mvc parsing 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);
}
Run Code Online (Sandbox Code Playgroud)

这是我试图解析的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"`
Run Code Online (Sandbox Code Playgroud)

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

什么是例外的原因?我之前使用过相同的方法,但效果很好.

请建议.

Chr*_*ers 10

尝试以下方法.

使用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();
Run Code Online (Sandbox Code Playgroud)

您从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;
}
Run Code Online (Sandbox Code Playgroud)

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

var json = ExtractJsonResponse(response);
Run Code Online (Sandbox Code Playgroud)

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

JObject o = JObject.Parse(json);
int total = (int)o["total"];
Run Code Online (Sandbox Code Playgroud)

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

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

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

https://api.stackexchange.com/docs