Error parsing JSON values in ASP.NET MVC?

2020-07-18 06:56发布

I am trying to use StackOverflow's search API to search questions.

I am using this action to perform the parsing :

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);
}

Here is the JSON url I am trying to parse:

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

I am trying to extract the following data:

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

Its giving error as : Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0.

What can be the reason for the exception? I used the same method earlier and it worked fine.

Please suggest.

2条回答
The star\"
2楼-- · 2020-07-18 07:28

My first guess since JsonReader gives an exception at line 0, position 0 is that something is messed up with the encoding. Since the request above shows the following Content-Type header in chrome developer tools

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

You can try to set the encoding WebClient uses to utf-8 via WebClient's Encoding property.

查看更多
Rolldiameter
3楼-- · 2020-07-18 07:40

Try the following approach.

Use NuGet and reference the JSON.NET package. I see you've already done this.

Compose a request and get the response.

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

The response you receive from the Stack Exchange API is gzipped! You first need to unzip it before you can read the JSON response. This is why you are receiving exceptions.

Let's create a method which does just that. .NET provides us with the handy GZipStream type for this purpose.

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;
}

Now you can extract the JSON data from the response.

var json = ExtractJsonResponse(response);

Now you can parse the returned data.

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

PS: I would recommend you use version 2.0 of the API which has been released earlier this year.

https://api.stackexchange.com/docs

查看更多
登录 后发表回答