Categories
.net asp.net c# http rest

RestSharp not deserializing JSON Object List, always Null

I’m having a problem with RestSharp deserializing the return content into my classes. From all my searching it seems that I am doing this correctly. I would much rather use RestSharp’s deserializer than have to fall back to another package like Newstonsoft’s Json.NET.

What I am doing is making a API request to GoToWebinar for all list of scheduled Webinars:

var client = new RestClient(string.Format("https://api.citrixonline.com/G2W/rest/organizers/{0}/upcomingWebinars", "300000000000239000"));
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "OAuth oauth_token=" + System.Configuration.ConfigurationManager.AppSettings["GoToWebinar"]);
var response2 = client.Execute<List<RootObject>>(request);

As you see I would like to get a list of object ‘RootObject’ (as shown below). I am receiving the following JSON response in response2.Content:

[
{
"webinarKey":678470607,
"subject":"Easton's Wild Rice Cooking Demo",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"organizerKey":300000000000239551,
"times":[{"startTime":"2012-05-09T15:00:00Z","endTime":"2012-05-09T16:00:00Z"}],
"timeZone":"America/Denver"
},
{
"webinarKey":690772063,
"subject":"Easton's Match Making Service",
"description":"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"organizerKey":300000000000239551,
"times":[{"startTime":"2012-05-09T15:00:00Z","endTime":"2012-05-09T16:00:00Z"}],
"timeZone":"America/Denver"
}
]

I created the following objects using http://json2csharp.com using the JSON results above:

public class RootObject
{
public int webinarKey { get; set; }
public string subject { get; set; }
public string description { get; set; }
public long organizerKey { get; set; }
public List<Time> times { get; set; }
public string timeZone { get; set; }
}
public class Time
{
public string startTime { get; set; }
public string endTime { get; set; }
}

The problem is response2.Data is always Null. For some reason the deserialization failed and I do not know why. My goal is to be able to use a foreach loop to iterate through the results:

foreach(RootObject r in response2.Data)
{
lblGoToWebinar.Text += r.webinarKey.ToString() + ", ";
}

Any ideas on why the deserialization is failing?

Based on the @agarcian’s suggestion above, I googled the error:

restsharp Data at the root level is invalid. Line 1, position 1.

and found this forum: http://groups.google.com/group/restsharp/browse_thread/thread/ff28ddd9cd3dde4b

Basically, I was wrong to assume that client.Execute was going to be able to auto-detect the return content type. It needs to be explicity set:

var request = new RestRequest(Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

This could be cited more clearly in RestSharp’s documentation. Hopefully this will help someone else out!