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!