Consuming JSON From WPF

August 9 2007

I want to throw up some prototype code that consumes JSON from WPF. (For more on JSON, see this article.) I put together that uses the JavaScriptSerializer to deserialize JSON into CLR objects, which could then be used for databinding. 

Here's what I did. First, I went and downloaded the ASP.NET AJAX framework.  Then, I created a new WPF project and added a reference the System.Web.Extensions dll, which got installed to C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions.  I then added the System.Web.Script.Serialization to my using statements.

To keep things simple, I wanted to prove I could convert this JSON:

{ "FirstName": "Karsten", "IsAlive": "true"}

 

Into this CLR type:

class Person
{
    public string FirstName;
    public bool IsAlive;
}

 

Turned out to be pretty simple.  Here's the code:

public Window1()
{
    InitializeComponent();
    JavaScriptSerializer jss = new JavaScriptSerializer();
    jss.RegisterConverters(new JavaScriptConverter[] { 
    new PersonConverter() });
    string test = "{\"FirstName\": \"Karsten\", \"IsAlive\": \"true\"}";
    Person p = jss.Deserialize<Person>(test);
    Person p = jss.d
}

Note how I register this thing called the PersonConverter after I instantiate the JavaScriptSerializer .  That's where all the work gets done and I'll discuss the PersonConverter below.  The only other interesting thing to note here is that to get the Person object,  I use the Deserialize<> method instead of the DeserializeObject(). This allows me to actually pass the type I want to have returned rather than attempting to cast the object afterward.

So, here's the code for the PersonConverter, which overrides the JavaScriptConverter :

class PersonConverter : JavaScriptConverter
{

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        Person p = new Person();
        p.FirstName = serializer.ConvertToType<string>(dictionary["FirstName"]);
        p.IsAlive = serializer.ConvertToType<bool>(dictionary["IsAlive"]);
        return p;
    }
    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        throw new Exception("The method or operation is not implemented.");
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new Type[] { typeof(Person)}; }
    }
}

The crux of the code here is in the override of Deserialize.  I followed the SDK documentation and made sure to use the ConvertToType method instead of doing the casting myself.  Basically, I just map each property from the JSON to the CLR object.  One could probably get fancy and use Reflection to do this dynamically, if you had everything singing.

I think I'll iterate on this a little more in a future post, but the net is that you can consume JSON into your WPF applications!

 


      

Comments (7) -

10/3/2007 9:42:00 AM #

Adam

Hello, thanks for sharing.
Any chance of converting this into VB?
thanks.
          

Adam

11/29/2008 1:42:00 AM #

Since writing this, .NET 3.5 ships with  DataContractJsonSerializer: msdn.microsoft.com/en-us/library/bb410770.aspx " target="_blank" >msdn.microsoft.com/en-us/library/bb410770.aspx

It's the bomb
          

Karsten Januszewski

4/20/2011 6:15:54 PM #

cheapjordans2011

Thanks for your write-up I truly learned something from it. Excellent posts on this website Usually looking forward to new post.

cheapjordans2011

4/30/2011 3:11:48 PM #

husqvarna chainsaw parts

What a great blog! It's a pity that i can't find your rrs address. If you can offer rrs subscription service, i can track your blog easier!

husqvarna chainsaw parts

5/16/2011 9:23:49 PM #

New Jordans 2011

Do you find it rational that they are suspicious connected with an full industry due to a very few terrible cheerios? There are actually not less than not one but two vital disparities, it appears to be with me. Initially, not one person worries this scientific research is proven to work, anything erroneous plus counterfeit lay claim could ever so often often be available. Nonetheless if there are actually every "miraculous" products out of faith-healing, above the male bodys private capability get rid of on its own, is rather a great deal during dilemma. The second thing is, a expose' with dupery plus blunder around scientific research created just about completely by way of scientific research. Although the vulnerability with dupery plus blunder around faith-healing will be under no circumstances executed by way of alternative faith-healers.

New Jordans 2011

7/3/2011 9:34:53 PM #

jibin

Hi if i use the code in the article
Person p = jss.Deserialize<Person>(test);
Person p = jss.d
Some errors are on the second line. P is already declared in this scoope and jss donot have an extension d.
Can someone please explain about these 2 lines
Thanks

jibin

7/3/2011 9:35:09 PM #

jibin

Hi if i use the code in the article
Person p = jss.Deserialize<Person>(test);
Person p = jss.d
Some errors are on the second line. P is already declared in this scoope and jss donot have an extension d.
Can someone please explain about these 2 lines
Thanks

jibin

7/3/2011 9:35:41 PM #

jibin

Hi if i use the code in the article
Person p = jss.Deserialize<Person>(test);
Person p = jss.d
Some errors are on the second line. P is already declared in this scoope and jss donot have an extension d.
Can someone please explain about these 2 lines
Thanks

jibin

Add comment

Enter your name, handle, alias, or email.

We'll incarnate your avatar from the services below.



biuquote
Loading