1

I would like to ask if anyone know how to extract out the "name" and "query" and maybe store it in a arraylist.

Source file: https://api.twitter.com/1/trends/daily.json

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
weikangchia
  • 537
  • 2
  • 6
  • 14

2 Answers2

2

You can use JObject , something like: -

 string response = requestData("https://api.twitter.com/1/trends/daily.json");
 JObject jsonResponse = new JObject();
 var name = string.Empty;
 var query = string.Empty;
 try
 {
       jsonResponse = JObject.Parse(response);
       name = (string)jsonResponse["name"];
       query = (string)jsonRespone["query"];
 }
 catch
 {
       return "";
 }

public string requestData(string url)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

    StreamReader sr = new StreamReader(resp.GetResponseStream());
    string results = sr.ReadToEnd();
    sr.Close();

    return results;
} 
dtsg
  • 4,408
  • 4
  • 30
  • 40
  • Hi thanks for the quick response. But when I tried just now, the value for name and query is actually null. – weikangchia Jun 07 '12 at 00:41
  • This is not a fully working implementation, only an example way of approaching the problem. I've used similar code to parse tweet counts from json data before so i know it's possible. – dtsg Jun 07 '12 at 07:42
  • Just had a look at your source data and looks like there's a `root` node `trends` that's interfering with it. Without the root node this task is trivial and the above would work. Unable to help you further I'm afraid... – dtsg Jun 07 '12 at 09:44
1

Based on this question: Parse JSON in C#

Make a class that represents the JSON you're extracting, and extract the class from the JSON using the code in the JSONHelper class from the linked question:

public class JSONHelper
{
    public static T Deserialise<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
        ms.Close();
        return obj;
    }
}
Community
  • 1
  • 1
Jon Egerton
  • 40,401
  • 11
  • 97
  • 129