<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Josh Holmes &#187; JSON</title>
	<atom:link href="http://www.joshholmes.com/blog/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.joshholmes.com/blog</link>
	<description>Random thoughts from a turbo nerd...</description>
	<lastBuildDate>Thu, 11 Apr 2013 15:51:31 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Playing with JSON</title>
		<link>http://www.joshholmes.com/blog/2009/01/20/playingwithjson/</link>
		<comments>http://www.joshholmes.com/blog/2009/01/20/playingwithjson/#comments</comments>
		<pubDate>Tue, 20 Jan 2009 18:00:39 +0000</pubDate>
		<dc:creator>joshholmes</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[JSON]]></category>

		<guid isPermaLink="false">http://www.joshholmes.com/blog/2009/01/20/PlayingWithJSON.aspx</guid>
		<description><![CDATA[I was asked on Friday by a friend how one can consume JSON in Silverlight. At the time, I just said start with the System.Json namespace and I&#8217;ll get you a sample later. Well, here&#8217;s a sample and a peek into my head because I couldn&#8217;t just stop with creating the sample that he needed. Download Solution &#8211; PlayingWithJSON.zip *Update &#8211; gotta do a quick shoutout to Leon Gersing for [...]]]></description>
				<content:encoded><![CDATA[<p><a title="Silverlight Plasma Reactor" href="http://www.flickr.com/photos/29995766@N07/2810870730/"><img class="flickr" border="0" hspace="5" alt="Silverlight Plasma Reactor" vspace="5" align="left" src="http://static.flickr.com/3093/2810870730_fcd17a398c_m.jpg"></a>I was asked on Friday by a friend how one can consume JSON in Silverlight. At the time, I just said start with the <a href="http://msdn.microsoft.com/en-us/library/system.json(VS.95).aspx">System.Json</a> namespace and I&#8217;ll get you a sample later. Well, here&#8217;s a sample and a peek into my head because I couldn&#8217;t just stop with creating the sample that he needed. </p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px" id="scid:18d43e01-4549-4fde-8ca6-c7b4b7385fac:10eb60d9-2305-4981-8cd1-e503ebfd55a2" class="wlWriterSmartContent">
<p>Download Solution &#8211; <a href="http://www.joshholmes.com/content/binary/WindowsLiveWriter/PlayingwithJSON_11097/PlayingWithJSON_4.zip">PlayingWithJSON.zip</a></p>
</div>
<p>*Update &#8211; gotta do a quick shoutout to <a href="http://www.fallenrogue.com">Leon Gersing</a> for his passionate defense of JavaScript and JSON. It&#8217;s part of what inspired me to spend as much time on this as I did. </p>
</p>
<h5>Really short JSON overview</h5>
<p><a href="http://json.org/">JSON</a>, for those of you who don&#8217;t know, is a really simple data format heavily used with <a href="http://jsconf2009.com/">JavaScript</a>. It&#8217;s a lot smaller and lighter than XML. </p>
<p>This is the JSON that I&#8217;m using in this example. As you can see, it&#8217;s just name/value pairs with a little bit of extra formatting. Curly Braces separate objects in a list. Commas separate values. Colons separate the names from the values.&nbsp; </p>
<p>[<br />{"FirstName":"Etta","LastName":"James","Url":"http:\/\/www.etta-james.com\/"},{"FirstName":"Billie","LastName":"Holiday","Url":"http:\/\/www.billie-holiday.net\/"},{"FirstName":"Ella","LastName":"Fitzgerald","Url":"http:\/\/en.wikipedia.org\/wiki\/Ella_Fitzgerald"}]<br />}</p>
<h5>Creating the JSON service with ASP.NET MVC Framework</h5>
<p>The first thing that I did was slap together an <a href="http://www.asp.net/mvc">ASP.NET MVC</a> Framework application to produce the JSON and host the Silverlight application. This was remarkably easy. I decided against going through the effort of creating a database because that&#8217;s not really the point of the exercise. </p>
<p>I created a simple class that to fill out and serialize and then returned it from a controller. </p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Artist
</span>{
    <span style="color: blue">public string </span>FirstName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>LastName { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Url { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
<p>The next step was to create a simple controller that would return my list as JSON. As you can see, there&#8217;s a JsonResult that you can return right from a controller method. </p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">ArtistsController </span>: <span style="color: #2b91af">Controller
</span>{
    <span style="color: blue">public </span><span style="color: #2b91af">JsonResult </span>GetAll()
    {
        <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt; artists = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt;();

        artists.Add(<span style="color: blue">new </span><span style="color: #2b91af">Artist</span>(<span style="color: #a31515">"Etta"</span>, <span style="color: #a31515">"James"</span>, <span style="color: #a31515">"http://www.etta-james.com/"</span>));
        artists.Add(<span style="color: blue">new </span><span style="color: #2b91af">Artist</span>(<span style="color: #a31515">"Billie"</span>, <span style="color: #a31515">"Holiday"</span>, <span style="color: #a31515">"http://www.billie-holiday.net/"</span>));
        artists.Add(<span style="color: blue">new </span><span style="color: #2b91af">Artist</span>(<span style="color: #a31515">"Ella"</span>, <span style="color: #a31515">"Fitzgerald"</span>, <span style="color: #a31515">"http://en.wikipedia.org/wiki/Ella_Fitzgerald"</span>));

        <span style="color: blue">return </span>Json(artists);
    }
}</pre>
<p>To test it, I just browsed to <a href="http://localhost:mylocalport/artists/getall">http://localhost:mylocalport/artists/getall</a>. That returned the JSON file. As the browser doesn&#8217;t display JSON auto-magically, it prompted me to download a file and save it off. </p>
<p>Now, take notice of the URL. The ASP.NET MVC Framework is producing what&#8217;s called a RESTful Service. The parameters and all are simply in the URL. In the URL, &#8220;artists&#8221; takes us to a particular Controller called the ArtistsController and the &#8220;getall&#8221; calls the &#8220;GetAll()&#8221; method on that controller. We can further specify parameters and the like in the URL. <a href="http://weblogs.asp.net/scottgu/">Scott Guthrie</a> has a great article that explains the URL routing and all at <a title="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx" href="http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx">http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx</a>. </p>
<p>Now that we are producing JSON from a services, we are ready to create a client. </p>
<h5>Getting the JSON from the RESTful service. </h5>
<p>The first client that I tried was the straight up System.Json namespace client. Since we are using a RESTful service, we can&#8217;t generate the proxy object in the same way that we&#8217;re used to with SOAP. Instead, we need to leverage the WebClient object.&nbsp; This is done as follows:</p>
<pre class="code"><span style="color: blue">void </span>mainButton_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">RoutedEventArgs </span>e)
{
    <span style="color: #2b91af">Uri </span>serviceUri = <span style="color: blue">new </span><span style="color: #2b91af">Uri</span>(<span style="color: #a31515">"/Artists/GetAll"</span>, <span style="color: #2b91af">UriKind</span>.Relative);
    <span style="color: #2b91af">WebClient </span>downloader = <span style="color: blue">new </span><span style="color: #2b91af">WebClient</span>();
    downloader.OpenReadCompleted += <span style="color: blue">new </span><span style="color: #2b91af">OpenReadCompletedEventHandler</span>(downloader_OpenReadCompleted);
    downloader.OpenReadAsync(serviceUri);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Notice that the URL that I&#8217;m using is relative. You can specify the full URL if the service is not on your own server. These calls, as all calls in Silverlight, are async. Therefore I wire up the downloader_OpenReadCompleted event and call OpenReadAsync. Simple enough?</p>
<h5>Leveraging System.Json</h5>
<p>Once the downloader returns, I can get the result off of the event arguments. Load is a static method on the JsonArray that will automatically parse out the results from the stream object. Then, I can just loop over the objects in the array and use them to fill out my own type that I&#8217;m ready to databind to. </p>
<pre class="code"><span style="color: blue">void </span>downloader_OpenReadCompleted(<span style="color: blue">object </span>sender, <span style="color: #2b91af">OpenReadCompletedEventArgs </span>e)
{
    <span style="color: #2b91af">JsonArray </span>jsonArray = (<span style="color: #2b91af">JsonArray</span>)<span style="color: #2b91af">JsonArray</span>.Load(e.Result);

    <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt; artists = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt;();

    <span style="color: blue">foreach </span>(<span style="color: #2b91af">JsonObject </span>jsonArtist <span style="color: blue">in </span>jsonArray)
    {
        <span style="color: #2b91af">Artist </span>artist = <span style="color: blue">new </span><span style="color: #2b91af">Artist</span>();
        artist.FirstName = jsonArtist[<span style="color: #a31515">"FirstName"</span>];
        artist.LastName = jsonArtist[<span style="color: #a31515">"LastName"</span>];
        artist.Url = jsonArtist[<span style="color: #a31515">"Url"</span>];

        artists.Add(artist);
    }

    dataGrid1.ItemsSource = artists;
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This was fairly straight forward and simple, but I wasn&#8217;t ready to be done yet. </p>
<h5>Leveraging LINQ</h5>
<p>The next thing is to try LINQ against this JsonArray and see what happens. </p>
<pre class="code"><span style="color: blue">void </span>downloader_OpenReadCompleted(<span style="color: blue">object </span>sender, <span style="color: #2b91af">OpenReadCompletedEventArgs </span>e)
{
    <span style="color: #2b91af">JsonArray </span>jsonArray = (<span style="color: #2b91af">JsonArray</span>)<span style="color: #2b91af">JsonArray</span>.Load(e.Result);

    <span style="color: blue">var </span>query = <span style="color: blue">from </span>artist <span style="color: blue">in </span>jsonArray
                <span style="color: blue">select new </span><span style="color: #2b91af">Artist
                </span>{
                    FirstName = (<span style="color: blue">string</span>)artist[<span style="color: #a31515">"FirstName"</span>],
                    LastName = (<span style="color: blue">string</span>)artist[<span style="color: #a31515">"LastName"</span>],
                    Url = (<span style="color: blue">string</span>)artist[<span style="color: #a31515">"Url"</span>],
                };

    <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt; artists = query.ToList() <span style="color: blue">as </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt;;
    dataGrid1.ItemsSource = artists;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Personally, I think that the LINQ version is a lot more powerful. It&#8217;s not immediately obvious in this simple example but there&#8217;s a ton that I could do with the LINQ query from filling out sub-types to filtering and so on. </p>
<h5>JSON in JavaScript </h5>
<p><a title="JavaScript Reference" href="http://www.flickr.com/photos/98624608@N00/64210142/"><img class="flickr" border="0" hspace="5" alt="JavaScript Reference" vspace="5" align="left" src="http://static.flickr.com/33/64210142_335dfd530e_m.jpg"></a>But then I started thinking about all of the different ways that one can get and parse out JSON directly in JavaScript (I mean it does have JavaScript right in the name). </p>
<p>First, I did it the old school way that I used to do back when I was doing a ton of JavaScript development. </p>
<p>Quick note here &#8211; before you start copying this code &#8211; this is NOT the way to do this in the modern era. I did it to prove a point. You really need to be leveraging one of the many great JavaScript frameworks that are out there in order to accomplish your JavaScript today. I&#8217;ll get to those in a minute. </p>
<p>Short version, you&#8217;re going to be doing an XMLHttpRequest directly. When that returns you&#8217;ll get an &#8220;onreadystatechange&#8221; event which you can respond to. If it&#8217;s actually ready, then you can call a JavaScript function called eval that will return and array of objects parsed out from the string that you pass in. </p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">language</span><span style="color: blue">="javascript" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;
    function </span>GetJson(url) {
        <span style="color: green">// Create xmlhttprequest object
        </span><span style="color: blue">var </span>xmlhttp = <span style="color: blue">null</span>;
        <span style="color: blue">if </span>(window.XMLHttpRequest) {
            xmlhttp = <span style="color: blue">new </span>XMLHttpRequest();
            <span style="color: green">//make sure that Browser supports overrideMimeType
            </span><span style="color: blue">if </span>(<span style="color: blue">typeof </span>xmlhttp.overrideMimeType != <span style="color: #a31515">'undefined'</span>) {
                xmlhttp.overrideMimeType(<span style="color: #a31515">'text/xml'</span>);
            }
        }
        <span style="color: blue">else if </span>(window.ActiveXObject) {
            xmlhttp = <span style="color: blue">new </span>ActiveXObject(<span style="color: #a31515">"Microsoft.XMLHTTP"</span>);
        }
        <span style="color: blue">else </span>{
            alert(<span style="color: #a31515">'Perhaps your browser does not support xmlhttprequests?'</span>);
        }

        <span style="color: green">// Create an HTTP GET request
        </span>xmlhttp.open(<span style="color: #a31515">'GET'</span>, url, <span style="color: blue">true</span>);

        <span style="color: green">// Set the callback function
        </span>xmlhttp.onreadystatechange = <span style="color: blue">function</span>() {
            <span style="color: blue">if </span>(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) {
                <span style="color: blue">var </span>json = xmlhttp.responseText;

                <span style="color: blue">var </span>artists = eval(json);

                <span style="color: blue">var </span>newArtistList;
                newArtistList = <span style="color: #a31515">"&lt;ul&gt;"</span>;

                <span style="color: blue">for </span>(<span style="color: blue">var </span>i <span style="color: blue">in </span>artists) {
                    <span style="color: blue">var </span>artist = artists[i];
                    newArtistList += <span style="color: #a31515">"&lt;li&gt;"
                    </span>+ artist.FirstName + <span style="color: #a31515">" "
                    </span>+ artist.LastName
                    + <span style="color: #a31515">"&lt;/li&gt;"
                </span>}

                newArtistList += <span style="color: #a31515">"&lt;ul&gt;"</span>;

                outputControl = document.getElementById(<span style="color: #a31515">"divOutput"</span>);
                outputControl.innerHTML = newArtistList;
            } <span style="color: blue">else </span>{
                <span style="color: green">// waiting for the call to complete
            </span>}
        };

        <span style="color: green">// Make the actual request
        </span>xmlhttp.send(<span style="color: blue">null</span>);
    }
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>Alright, that&#8217;s a lot of JavaScript to get through and understand. There are multiple possible problems here. First, that&#8217;s just a ton of code. Second, the same eval function that you are calling here is the same eval function used to dynamically execute a piece of JavaScript in a string. This means that you&#8217;re open to all kinds of possible attacks. Finally, there are a ton of frameworks that have come up in the past handful of years. </p>
<p>So, let&#8217;s go look at some of those frameworks. </p>
<h5>Leveraging MS AJAX</h5>
<p>The AJAX framework that I&#8217;ve been trying to learn lately is the <a href="http://ajax.asp.net/">MS AJAX</a> one. It&#8217;s got a lot of power. First, notice that the WebRequest actually looks a lot like what I did in C#. Next, notice the JavaScriptSerializer object. This gives me some nice and easy serialization to and from JSON. The reason to use this is that it&#8217;s a much safer mechanism than eval. Lastly, notice the $get at the end. This is a nice and easy selector that does all of the heavy lifting of finding the object in the DOM and the like. </p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">src</span><span style="color: blue">="../../Scripts/MicrosoftAjax.js" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;</span>
<span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">language</span><span style="color: blue">="javascript" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;
    function </span>GetJson() {
        <span style="color: blue">var </span>request = <span style="color: blue">new </span>Sys.Net.WebRequest();
        request.get_headers()[<span style="color: #a31515">'Content-Type'</span>] = <span style="color: #a31515">'application/json; charset=utf-8'</span>;
        request.set_url(<span style="color: #a31515">'/Artists/GetAll'</span>);

        request.add_completed(Function.createDelegate(<span style="color: blue">null</span>, DisplayArtists));
        request.invoke();
    }

    <span style="color: blue">function </span>DisplayArtists(executor) {
        <span style="color: blue">if </span>(executor.get_responseAvailable()) {
            <span style="color: blue">var </span>json = executor.get_responseData();
            <span style="color: blue">var </span>artists = Sys.Serialization.JavaScriptSerializer.deserialize(json);

            <span style="color: blue">var </span>newArtistList;
            newArtistList = <span style="color: #a31515">"&lt;ul&gt;"</span>;

            <span style="color: blue">for </span>(<span style="color: blue">var </span>i <span style="color: blue">in </span>artists) {
                <span style="color: blue">var </span>artist = artists[i];
                newArtistList += <span style="color: #a31515">"&lt;li&gt;"
                </span>+ artist.FirstName + <span style="color: #a31515">" "
                </span>+ artist.LastName
                + <span style="color: #a31515">"&lt;/li&gt;"
            </span>}

            newArtistList += <span style="color: #a31515">"&lt;ul&gt;"</span>;

            $get(<span style="color: #a31515">"divOutput"</span>).innerHTML = newArtistList;
        }
    }
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
</span></pre>
<p>This is a lot less code and a lot safer than what I was doing in raw JavaScript. However, I thought I should try this with a few more frameworks. </p>
<h5>Leveraging Prototype</h5>
<p><a href="http://www.joshholmes.com/content/binary/WindowsLiveWriter/PlayingwithJSON_11097/image_4.png"><img style="border-right-width: 0px; margin: 5px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="image" align="left" src="http://www.joshholmes.com/content/binary/WindowsLiveWriter/PlayingwithJSON_11097/image_thumb_1.png" width="173" height="81"></a> A framework that I&#8217;ve used for a while and really like is <a href="http://prototypejs.org/">Prototype</a>. </p>
<p>This is a whole lot less code. Notice the &#8220;Ajax.Request&#8221;. That packages up all of the work of doing the network call behind one simple to use function. And on the response is a nice and easy method called evalJSON that will parse out the JSON string to an array of objects that you can loop over. Finally, notice the $() selector. </p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">src</span><span style="color: blue">="../../Scripts/prototype-1.6.0.2.js" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
&lt;</span><span style="color: #a31515">script </span><span style="color: red">language</span><span style="color: blue">="javascript" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;
    function </span>GetJson() {
        <span style="color: blue">new </span>Ajax.Request(<span style="color: #a31515">'/Artists/GetAll'</span>, {
            method: <span style="color: #a31515">'get'</span>,
            onSuccess: DisplayArtists
        })
      }

      <span style="color: blue">function </span>DisplayArtists(transport) {
        <span style="color: blue">var </span>json = transport.responseText.evalJSON();
        <span style="color: blue">var </span>newArtistList;
        newArtistList = <span style="color: #a31515">"&lt;ul&gt;"</span>;

        json.each(<span style="color: blue">function</span>(artist) {
            newArtistList += <span style="color: #a31515">"&lt;li&gt;"
                    </span>+ artist.FirstName + <span style="color: #a31515">" "
                    </span>+ artist.LastName
                    + <span style="color: #a31515">"&lt;/li&gt;"
        </span>});

        newArtistList += <span style="color: #a31515">"&lt;ul&gt;"</span>;

        $(<span style="color: #a31515">"divOutput"</span>).insert(newArtistList);
    }
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I liked this a lot. A feature that I didn&#8217;t take advantage of is that <a href="http://script.aculo.us/">Scriptaculous</a>, which is a fantastic set of JavaScript libraries for visualization, weaves in with <a href="http://prototypejs.org/">Prototype</a> really easily. </p>
<h5>Leveraging <a href="http://jquery.com/">jQuery</a></h5>
<p><a href="http://www.joshholmes.com/content/binary/WindowsLiveWriter/PlayingwithJSON_11097/image_2.png"><img style="border-right-width: 0px; margin: 5px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="image" align="left" src="http://www.joshholmes.com/content/binary/WindowsLiveWriter/PlayingwithJSON_11097/image_thumb.png" width="244" height="75"></a> The last JavaScript framework that I tried was <a href="http://jquery.com/">jQuery</a>. One extra cool part about this one for me is that I get intellisense right in Visual Studio. Check out Scott Guthrie&#8217;s post on <a href="http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx">jQuery Intellisense in VS2008</a> to see how to enable it. </p>
<p>Notice that it&#8217;s got the same type of easy to use function that packages up the call to get the JSON. Since it knows that it&#8217;s JSON, the variable returned to the callback is already parsed out into a usable object. And lastly, notice the $() selector again. There is a subtle difference between this one and the Prototype selector in that the <a href="http://jquery.com/">jQuery</a> one uses a # to signify that it&#8217;s looking for an ID, . to signify objects with a given class and so on. </p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">language</span><span style="color: blue">="javascript" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;
    function </span>GetJson() {
        $.getJSON(<span style="color: #a31515">"/Artists/GetAll"</span>,
          {},
          DisplayArtists);
      }

      <span style="color: blue">function </span>DisplayArtists(data) {
          <span style="color: blue">var </span>newArtistList;
        newArtistList = <span style="color: #a31515">"&lt;ul&gt;"</span>;

        <span style="color: blue">for</span>(<span style="color: blue">var </span>i = 0; i &lt; data.length;i++)
        {
            <span style="color: blue">var </span>artist = data[i];
            newArtistList += <span style="color: #a31515">"&lt;li&gt;"
                </span>+ artist.FirstName + <span style="color: #a31515">" "
                </span>+ artist.LastName
                + <span style="color: #a31515">"&lt;/li&gt;"
        </span>}

        newArtistList += <span style="color: #a31515">"&lt;ul&gt;"</span>;

        $(<span style="color: #a31515">"#divOutput"</span>).html(newArtistList);
    }
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now that I was done playing with different JavaScript libraries, I thought I&#8217;d see if I could piece it all back together. </p>
<h5>Leveraging jQuery and Silverlight</h5>
<p>I decided to try <a href="http://jquery.com/">jQuery</a> and Silverlight together, leveraging <a href="http://jquery.com/">jQuery</a> to get and parse the JSON and Silverlight to do the display. This turned out to be remarkably simple. </p>
<p>First, in order for Silverlight to call into the JavaScript, you just have to call HtmlPage.Window.Invoke. That dynamically looks up and executes the method named in the first parameter. </p>
<pre class="code"><span style="color: blue">void </span>mainButton_Click(<span style="color: blue">object </span>sender, <span style="color: #2b91af">RoutedEventArgs </span>e)
{
    <span style="color: #2b91af">HtmlPage</span>.Window.Invoke(<span style="color: #a31515">"GetJson"</span>, <span style="color: #a31515">"/Artists/GetAll"</span>);
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now, I could have wired up the JavaScript to listen for the button click event directly but that&#8217;s a lot more code than what I&#8217;ve got here. </p>
<p>Next I had to enable the Silverlight objects for callbacks. Step 1 is to Register the class with the browser&#8217;s scripting engine.</p>
<pre class="code"><span style="color: blue">public </span>LeveragingJQuery()
{
    InitializeComponent();
    <span style="color: #2b91af">HtmlPage</span>.RegisterScriptableObject(<span style="color: #a31515">"LeveragingJQuery"</span>, <span style="color: blue">this</span>);
...<br />}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Step 2 is to declare one of the methods as a ScriptableMember. This gives the scripting engine access to the method in question. There&#8217;s also ScriptableType for creating serializable objects but that&#8217;s not what we need here. Notice, however, that the object type passed in is a ScriptObject. The slick part about this object is that it&#8217;s got a &#8220;ConvertTo&#8221; method that will take the weakly typed objects that it contains and serialize them to the type of object that you specify. This made the C# code here REALLY simple. </p>
<pre class="code">[<span style="color: #2b91af">ScriptableMember</span>]
<span style="color: blue">public void </span>CallBackFromJavaScript(<span style="color: #2b91af">ScriptObject </span>artists)
{
    <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt; listofartists = artists.ConvertTo&lt;<span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Artist</span>&gt;&gt;();
    dataGrid1.ItemsSource = listofartists;
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>What&#8217;s left is the <a href="http://jquery.com/">JQuery</a> in the browser that we&#8217;re talking to. Notice that the first part is exactly the same. The second part, however, is a little different. First, we have to get a reference to the Silverlight plugin itself. Since I&#8217;m in a form object, ASP.NET mangles the name a little bit but it wasn&#8217;t too hard to figure out the new name. Next, I have to get the object that I had registered with the RegisterScriptableObject method. Then, all that&#8217;s left is calling the method to pass in my array of Artists. </p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">src</span><span style="color: blue">="/Scripts/jquery-1.2.6.js" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
&lt;</span><span style="color: #a31515">script </span><span style="color: red">language</span><span style="color: blue">="javascript" </span><span style="color: red">type</span><span style="color: blue">="text/javascript"&gt;
    function </span>GetJson(url) {
        $.getJSON(url,
          {},
          DisplayArtists);
    }

    <span style="color: blue">function </span>DisplayArtists(artists) {
        <span style="color: blue">var </span>control = document.getElementById(<span style="color: #a31515">"ctl00_MainContent_SilverlightPlugin"</span>);
        <span style="color: blue">var </span>leveragingJSPage = control.Content.LeveragingJQuery;
        leveragingJSPage.CallBackFromJavaScript(artists);
    }
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h5>Conclusion</h5>
<p>This is how I learn about new things. I&#8217;m not satisfied with just getting the job done in one and only one way. I want to try out 3, 4, 5 different ways to accomplish a given task. That way I know what the right way to do something is in a given context. For example, I don&#8217;t know that I&#8217;ll ever need to mingle <a href="http://jquery.com/">jQuery</a> and Silverlight. But, I know how it&#8217;s done now and know that it&#8217;s a lot simpler than I originally thought it would be. </p>
<p>JSON is a simple but powerful format. There are a ton of simple services, from flickr to twitter to many of your production applications that could be producing JSON. It saves bandwidth compared to XML and is a just as simple to use. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.joshholmes.com/blog/2009/01/20/playingwithjson/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>
