
So, I wanted to build a simple display for the foyer of our building that would display in real-time the zeitgeist of the nation. What better way of testing the pulse of the UK, than pulling down the latest list of Twitter Trends.
Twitter exposes this as a nice bit of JSON XML
If you call - http://api.twitter.com/1/trends.json
You get a nice JSON response explained fully here
https://dev.twitter.com/docs/api/1/get/trends/current
.Net 4.0 has a great JSON deseriliser that can quickly read inbound JSON and turn into nicely populated .net classes.
My base class to represent the data from my feed looks like -
using System.Runtime.Serialization;
namespace Trends
{
[DataContract]
public class OurTrend
{
[DataMember(Name = "trends")]
public List<Trend> trends { get; set; }
[DataMember(Name = "as_of")]
public string AtDate {get;set;}
}
}
Each trending topic is then held in a ‘Trend’ class which looks like -
using System.Runtime.Serialization;
using System.Runtime.Serialization;
namespace Trends
{
[DataContract]
public class Trend
{
[DataMember(Name = "url")]
public string Url { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
}
}
Note the DataContract and DataMember tags, are what instructs the deserialization of the JSON.
Using the magic of System.Runtime.Serialization.Json you can read contents straight into .Net.
Like -
string response = "{\"trends\":[{\ ....
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OurTrend));
byte[] inbytes = Encoding.UTF8.GetBytes(response);
MemoryStream ms = new MemoryStream(inbytes);
ms.Position = 0;
OurTrend data = (OurTrend)serializer.ReadObject(ms);
ms.Dispose();
Contact Me, via my blog if you would like a copy of the full source.