This is a follow on question to this one Serialize deserialize anonymous child JSON properties to model
I am able to deserialize the JOSN correctly now when my data is as follows using dictionary objects for the Location field
{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":{"103":"Cambridge","107":"London"}}
Yet I run into problems when there is no values in the array, ie sometimes there is data like this
{"id":"2160336","activation_date":"2013-08-01","expiration_date":"2013-08-29","title":"Practice Manager","locations":[]}
Any suggestions? Would be easy if i could have a nullable dictionary but I can't have that right?
my classes look like this:
public class ItemResults
{
public int Id { get; set; }
public DateTime Activation_Date { get; set; }
public DateTime Expiration_Date{ get; set; }
public string Title { get; set; }
public Dictionary<string, string> Locations { get; set; }
}
and I have tried deserializing using JavaScriptSerializer and Newtonsoft JSON.net deserializer both with the same error.
OK this here gave me the solution to the problem How to deserialize object that can be an array or a dictionary with Newtonsoft?
public Dictionary<string, string> Location_Options
{
get
{
var json = this.LocationsJson.ToString();
if (json == string.Empty | json == "[]")
{
return new Dictionary<string, string>();
}
else
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
}
}
}
[JsonProperty(PropertyName = "Locations")]
public object LocationsJson { get; set; }
Many thanks for your help everyone