Google Data API with RestSharp on WP7 Update

Special thanks to John Sheenan who pointed out an error in my code. First of all, calling Dispatcher.BeginInvoke is redundant since the callback action will be invoked on the main thread.

Secondly, there is a powerful deserialization feature in RestSharp. Create a simple class that will correspond to the deserialized JSON object:

public class oauth2_device_code
{
    public string device_code { get; set; }
    public string expires_in { get; set; }
    public string interval { get; set; }

    public string user_code { get; set; }
    public string verification_url { get; set; }
}

You can execute request using the generic version of RestClient.ExecuteAsync:

_clientOAuth.ExecuteAsync<oauth2_device_code>(request, (response) =>
{
	IsolatedStorageSettings.ApplicationSettings["device_code"] = response.Data.device_code;
	IsolatedStorageSettings.ApplicationSettings["expires_in"] = response.Data.expires_in;
	IsolatedStorageSettings.ApplicationSettings["interval "] = response.Data.interval;
	IsolatedStorageSettings.ApplicationSettings.Save();
}

This class matches the following JSON response:

{
  "device_code" : "...",
  "user_code" : "...",
  "verification_url" : "http://www.google.com/device",
  "expires_in" : 1800,
  "interval" : 5
}

However, if you form a bad request, you might get the following JSON response:

{
  "error" : "invalid_client"
}

By adding another property to the oauth2_device_code class (see example below), RestSharp will fill it and you can use the request’s StatusCode property to determine if there was an error. The library will try to match as many properties as it can and fill them accordingly. The best thing is that the C# property names do not need to be named the same way their corresponding fields in JSON are. E.g. the device_code field in JSON will match and fill the DeviceCode class property in the C# code.

public class oauth2_device_code
{
    // ...
    public string error { get; set; }
}

RestSharp can also deserialize XML responses in the same vein. This powerful feature does not impact your naming convention, which is clearly a benefit.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Last updated by at .