I'm trying to loop through a json file and retrieve the title of each record from a yahoo api. Can someone please give me some pointers as to how I need to do this. My code is as follows:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%20and%20location%3D%22san%20francisco%2C%20ca%22&format=json&diagnostics=true&callback=cbfunc");
HttpWebResponse rep = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(rep.GetResponseStream());
string data = sr.ReadToEnd();
//Console.WriteLine(data);
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string,string>>(data);
You could design a couple of classes to match the JSON structure returned by yahoo. Also don't use the callback=cbfunc
parameter because otherwise yahoo returns JSONP instead of JSON:
using System;
using System.Net;
using System.Web.Script.Serialization;
public class YahooResponse
{
public Query Query { get; set; }
}
public class Query
{
public Results Results { get; set; }
}
public class Results
{
public Result[] Result { get; set; }
}
public class Result
{
public string Title { get; set; }
}
class Program
{
static void Main()
{
using (var client = new WebClient())
{
var json = client.DownloadString("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20query%3D%22sushi%22%20and%20location%3D%22san%20francisco%2C%20ca%22&format=json&diagnostics=true")
var jss = new JavaScriptSerializer();
var result = jss.Deserialize<YahooResponse>(json);
foreach (var item in result.Query.Results.Result)
{
Console.WriteLine(item.Title);
}
}
}
}