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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With