WindowsPhoneGeek

WPAppInfo

Login | Join (Why?)

rss rss rss
logo

Getting latest Tweets in Windows Phone apps using Twitter REST API and JSON.NET

published on: 1/31/2012 | Views: N/A | Tags: wp7dev

by WindowsPhoneGeek

In this article I am going to talk about using the Twitter Rest API and JSON.NET in Windows Phone apps to show the latest 10 tweets from a particular Twitter account.

Before we begin, make sure that you have took a look at the Twitter Rest API Documentation:

https://dev.twitter.com/docs/api/1/get/statuses/user_timeline

Is short we will use the following uri to get winphonegeek's latest tweets:

https://api.twitter.com/1/statuses/user_timeline.json?trim_user=true&screen_name=winphonegeek&count=10

The above url returns data about tweets in JSON format that looks like this:

{
    possibly_sensitive: false,
    in_reply_to_screen_name: "@WPAppInfo",
    truncated: false,
    retweeted: false,
    in_reply_to_user_id: 171279759,
    in_reply_to_status_id_str: null,
    coordinates: null,
    in_reply_to_user_id_str: "171279759",
    user: {
        id_str: "198796409",
        id: 198796409
    },
    id_str: "164047529783209984",
    place: null,
    geo: null,
    contributors: null,
    source: "web",
    retweet_count: 0,
    favorited: false,
    id: 164047529783210000,
    in_reply_to_status_id: null,
    text: "tweet text",
    created_at: "Mon Jan 30 18:09:13 +0000 2012"
}

We will also use Json.NET: a popular free high-performance JSON framework for .NET available on CodePlex. To summarize we will use Json.NET to deserialize (read) the Json formatted Twitter data into .NET objects.

Step1. Add reference to "Newtonsoft.Json.dll" from Json.NET

image

Step2. Next, we will create a simple class that will be used to deserialize the Twitter data into objects.

public class Tweet
{
    public string Text
    {
        get;
        set;
    }

    [JsonProperty("created_at")]
    public string CreatedAt
    {
        get;
        set;
    }

    public string Source
    {
        get;
        set;
    }

    [JsonProperty("retweet_count")]
    public int RetweetCount
    {
        get;
        set;
    }
}

NOTE: You will also have to add the following using statement:

using Newtonsoft.Json;

Step3. After that, we will add a ListBox and a button to the MainPage.xaml

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    
    <ListBox x:Name="lbTweets">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="{Binding Text}" TextWrapping="Wrap" />
                    <TextBlock Text="{Binding CreatedAt}" Style="{StaticResource PhoneTextSubtleStyle}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    
    <Button x:Name="btnRefreshTweets" Grid.Row="1" 
            Content="Refresh tweets"
            Click="btnRefreshTweets_Click"/>
</Grid>

Step4. Finally, in the button click event handler, we start an async download using the above url to download the latest Twitter data:

private void btnRefreshTweets_Click(object sender, RoutedEventArgs e)
{
    string winPhoneGeekTweetsUrl = @"https://api.twitter.com/1/statuses/user_timeline.json?trim_user=true&screen_name=winphonegeek&count=10";

    WebClient webClient = new WebClient();
    webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(new Uri(winPhoneGeekTweetsUrl));
}

NOTE: In the above string URl "screen_name" is the name of the Twitter account that you want to get data for and "count" is the number of the tweets you want to get.

Step4. When the download completes, we use JSON.NET to deserialize the json data into a list of Tweet object and set it as the items source of the list box.(NOTE: Tweet is the class created in Step2 above):

void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error != null)
    {
        return;
    }
    List<Tweet> tweets = JsonConvert.DeserializeObject<List<Tweet>>(e.Result);
    this.lbTweets.ItemsSource = tweets;
}

Step5. That`s it. just build and run the project to see the result:

image image

Here is the full source code:

I hope that the post was helpful.

You can also follow us on Twitter @winphonegeek

Comments

Add comment to 'Getting latest Tweets in Windows Phone apps using Twitter REST API and JSON.NET'

Comment

Our Top Articles & Free books

Our Top Tips & Samples