Posts tagged ‘json’

Json in C# – Part 2

I posted before Json in C# but I was not satisfied with what I found so far. I went looking again and found some C# classes in the newer frameworks. namely JavaScriptSerializer. Let’s take a look with a simple json data feed.

using System.Web.Script.Serialization;
   
    internal static class Program
    {
        class CarList
        {
            public List<Car> cars;
        }
        class Car
        {
            public string model = string.Empty;
            public int year = 0;
        }

        private static void Main(string[] args)
        {
            string jsonString = “{\”cars\”:[{\”model\”:\”Ford 350\”,\”year\”:2007},{\”model\”:\”Buick Skylark\”,\”year\”:1953},{\”model\”:\”Honda Civic\”,\”year\”:2002}]}”;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            CarList carObjects = serializer.Deserialize<CarList>(jsonString);
            Console.WriteLine(“cars count=” + carObjects.cars.Count);
        }



As far as I can tell JavaScriptSerializer was introduced in .Net 3.0, but depreciated in 3.5. Instead your supposed to use DataContractJsonSerializer. With that change you need to add serialize attribute to your classes, you also need to include Xml and serialization libs. Let’s take a look at the new code.

using System.Runtime.Serialization.Json;

    internal static class Program
    {
        [Serializable]
        class CarList
        {
            public List<Car> cars;
        }
        [Serializable]
        class Car
        {
            public string model = string.Empty;
            public int year = 0;
        }

        private static void Main(string[] args)
        {
            string jsonString = “{\”cars\”:[{\”model\”:\”Ford 350\”,\”year\”:2007},{\”model\”:\”Buick Skylark\”,\”year\”:1953},{\”model\”:\”Honda Civic\”,\”year\”:2002}]}”;
            //         
            DataContractJsonSerializer jsonserialize = new DataContractJsonSerializer(typeof(CarList));
            Stream jsonStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString));
            CarList carObjectsj = (CarList)jsonserialize.ReadObject(jsonStream);
            Console.WriteLine(“cars count=” + carObjectsj.cars.Count);
        }



As a curve ball Microsoft decided to Un-depreciate the JavaScriptSerializer in .Net 3.5 SP1, which is good news. It’s easier coding when using the JavaScriptSerializer. I don’t know if both classes will be permanently available, we will see.

Json in C#

I did some Json work in C#, I hadn’t done any Json with C# before.  Naturally I go googling without much luck at first.  When you look for Json libraries and code snippets they are plentiful, but most of them java script browser stuff.  Then a friend pointed out Jayrock which was exactly what I needed.  It can be used in C# code to address Json feed similar to Xml feeds.

As mentioned before json is extremely java script friendly.  Let’s take a look at one of the Google examples.

<h3>Upcoming Google Developer Events</h3>
<div id=“agenda”></div>
<script>
  function listEvents(root) {
    var feed = root.feed;
    var entries = feed.entry || [];
    var html = [‘<ul>’];

    for (var i = 0; i < entries.length; ++i) {
      var entry = entries[i];
      var title = entry.title.$t;
      var start = (entry[‘gd$when’]) ? entry[‘gd$when’][0].startTime : “”;     
      html.push(‘<li>’, start, ‘ – ‘, title, ‘</li>’);
    }
    html.push(‘</ul>’);
    document.getElementById(“agenda”).innerHTML = html.join(“”);
  }
</script>

<script src=“http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json-in-script&callback=listEvents”>
</script>

Run the sample.

And then in C# using Jayrock

using Jayrock.Json;

WebClient client = new WebClient();
Uri url = new Uri(“http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json”);
string gevents= client.DownloadString(url);

using (JsonTextReader reader = new JsonTextReader(new StringReader(gevents)))
{

    while (reader.Read())
    {
        if (reader.Depth == 4 &&
            reader.TokenClass == JsonTokenClass.Member &&
            reader.Text != null )
        {
            if (reader.Text.Equals(“gd$when”))
            {
                // navigate to the right node
                for( int i = 0; i < 6; i++)
                    reader.Read();
               
                // startTime
                Console.WriteLine(reader.ReadString());
            }
            else if (reader.Text.Equals(“title”))
            {
                // navigate to the right node
                for (int i = 0; i < 5; i++)
                    reader.Read();

                // $t
                Console.WriteLine(reader.ReadString());
            }
        }
    }
}

Those for loops are a bit ugly to get down the tree to the correct node. There has to be a better way of doing that. With simple data pairs it’s no problem but with heavier feeds like the one I took in the sample it’s not as obvious. If you have a simpler or more elegant way of doing it in C# drop a comment.

This is what the Json feed looks like.

Here are some tools, that I came up on JsonViewer which is hosted on CodePlex. The viewer also comes with a plugin for Fiddler, which is really handy and also has one for VS. Fiddler is a http debugging proxy. CodePlex is Microsoft’s answer to sourceforge.

You can find extensive list of json libraries here, for bunch of different languages.

Tweet trends

I just played with the Twitter api / links to get to know it.  Took their trend feed which is a json stream.  The stream includes names of the trends and it’s URL.   After the json info is imported the next thing is to hit the RSS / Xml feed for each topic.  Load it into entry objects including authors and spit out the ones that include links, up to the last three per category.  As that’s what gives you the best bang for the buck checking on Tweet trends.  You can take a look at it here.  The feed it self is live and updates real time, but you have to refresh the page to get the latest.  Thanks to @johnadepue for his input.

Then I went on Twitter Grader for fun.  It turns out I’m in negative territory.  My ranking shows up as “57,255 Overall rank, out of 56,047“  Althought I only been a few days on Twitter that doesn’t feel right.   I’m graded a bit less than the whole Twitter population.  How is that for a math problem.