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.
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
You can try to set the encoding WebClient uses to utf-8 via WebClient's Encoding property.
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.
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.
Now you can extract the JSON data from the response.
Now you can parse the returned data.
PS: I would recommend you use version 2.0 of the API which has been released earlier this year.
https://api.stackexchange.com/docs