Share via


Twitter trends - the easy way to display trends :)

Ok, I was playing around with the Twitter Trends https://search.twitter.com/trends/current.json.

I wanted to display the current trends on a page or wherever so I decided to give it a go with Linq to JSON, featured in JSON.NET.

I ran into some problems since the property in the json post is changing all the time so I don't have a static property to call in my code.

The easiest way that I found, was to replace the datetime tag with some static text and use that in my LINQ query.

So here goes:

using System;
using System.IO;
using System.Linq;
using System.Net;
using Newtonsoft.Json.Linq;

namespace TwitterCmd
{
class Program
{
static void Main(string[] args)
{
string input = GetInput();
string thisYear = DateTime.Now.Year.ToString();
string date = input.Substring(input.IndexOf(thisYear), 19);
input = input.Replace(date, "herewasdate");
JObject trends = JObject.Parse(input);
var TwitterTrends = from t in trends["trends"]["herewasdate"]
select t.Value<string>("name");
foreach (var twitterTrend in TwitterTrends)
{
Console.WriteLine(twitterTrend);
}
Console.ReadLine();
}

    private static string GetInput()
{
WebRequest request = WebRequest.Create("https://search.twitter.com/trends/current.json");
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string input = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return input;
}
}
}

This will list the current trends from Twitter.

Let me know if you know the way of querying a property that is ever changing! :)