2

I'm a beginner in C# and JSON, I've only been coding in Java (Basic stuff like reading/writing files, hashmaps, etc., no web development whatsoever, beginner programmer)

I'm a student and have been tasked to code a console app in C# which interacts with twitter. For now, I'm stuck with extreme basics. I'm trying to get tweets in a public timeline using JSON and C#. I've been successful with doing this through the use of Twitterizer, but I only found out recently that I cannot use 3rd-party libraries (other than NewtonSoft.JSON.dll), and must code everything from scratch. I would really appreciate it if someone could provide me with sample code that does this and preferably prints out the latest tweet and its corresponding user from the public timeline, so that I can roughly know how how data is read and used.

My understanding of JSON and C# is extremely limited, but this is what I know I'm supposed to do for a start:

  1. WebRequest w1 = WebRequest.Create("http://api.twitter.com/1/statuses/public_timeline.json");
  2. w1.getResponse();
  3. I don't know what to do / how to parse JSON files

Thank you

Procrastinatus
  • 121
  • 2
  • 12

1 Answers1

3

This can be a starting point. (You can also use Json Viewer to get a formatted version of your json)

using (WebClient webClient = new WebClient())
{
    string url = "http://api.twitter.com/1/statuses/public_timeline.json";
    dynamic json = JsonConvert.DeserializeObject(webClient.DownloadString(url));

    foreach (var item in json)
    {
        Console.WriteLine("{0} {1}", item.user.id, item.user.screen_name);
    }
}

PS: JsonConvert is a part of NewtonSoft library

L.B
  • 114,136
  • 19
  • 178
  • 224
  • Thank you, it works! Just that... I get an unhandled exception sometimes - http://oi50.tinypic.com/2mq8y.jpg I could just put in a try-catch, but then I wouldn't know why it doesn't work I also get 503s sometimes, I want to confirm if this is due to Twitter's limit on the streaming API or something – Procrastinatus May 20 '12 at 13:11
  • My guess you hit the Twitter API limits. You can also try Twitters' streaming API http://stackoverflow.com/questions/9779766/tweetsharp-and-api-streaming – L.B May 20 '12 at 13:44
  • From what I see in https://dev.twitter.com/docs/streaming-apis/connecting#HTTP_Error_Codes , I don't think it's the limits that are causing the unhandled exception in the previous reply, if it were the limits, wouldn't I have gotten a proper error code instead? – Procrastinatus May 20 '12 at 15:04