Creating JSON-enabled ViewModels

July 17, 2011 | WPF

Recently, Ian Randall contributed something really cool to the DynamicViewModel codebase: Support for binding to a JSON object. I find this exciting! 

In the trunk of DynamicViewModel you can find an example that uses the Stack Exchange API. It is a WPF application for searching the Stack Overflow Users. 

Screenshot of the demo application

All API responses are JSON in Stack Exchange API. Ian took advantage of that and wrote a DynamicViewModelFactory that contains the factory method below:

public static DynamicViewModel Create(string json)
{
    DynamicViewModel result;
    if (!json.TryCreateDynamic(out result))
    {
        throw new ArgumentException("parameter was not a valid JSON string");
    }

    return result;
}

This factory method creates an instance of a DynamicViewModel from a JSON formatted string. In order to use it you need to write code similar to the one below:

var uriString = "http://api.stackoverflow.com/1.1/users?filter=" + e.Argument;
var request   = CreateHttpWebRequest(uriString);
var response  = request.GetResponse();

using (var streamReader = new StreamReader(response.GetResponseStream()))
{
    var json = streamReader.ReadToEnd();
    dynamic viewModel = DynamicViewModelFactory.Create(json);
}

And some XAML action:

<TextBlock
    Grid.Column="0"
    VerticalAlignment="Center"
    Margin="4,0,0,0"
    Text="{Binding display_name}" />
<TextBlock
    Grid.Column="1"
    VerticalAlignment="Center"
    Text="{Binding reputation}" />

<local:BadgesUserControl
    Grid.Column="2"
    DataContext="{Binding badge_counts}" />

The source code is here. Thanks to Ian Randall!