Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error parsing JSON values in ASP.NET MVC?

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.

like image 254
Man8Blue Avatar asked Dec 16 '22 23:12

Man8Blue


1 Answers

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

like image 138
Christophe Geers Avatar answered Dec 21 '22 22:12

Christophe Geers