I am trying to deserialize a JSON response, but I am doing something wrong when creating the data models.
I deserialize normally with EventsData resultJSON = JsonConvert.DeserializeObject<EventsData>(jsonText);
JSON contains list of events such as:
{
"@event_no":"6924",
"@name":"REDACTED",
"Show":{
"@show_no":"1",
"@show_datetime":"2007-04-05 15:00:00"
}
},
{
"@event_no":"6925",
"@name":"REDACTED",
"Show":{
"@show_no":"1",
"@show_datetime":"2007-04-15 15:00:00"
}
}
My data model:
public class Show
{
[JsonProperty("@show_no")]
public string show_no { get; set; }
[JsonProperty("@show_datetime")]
public string show_datetime { get; set; }
}
public class Event
{
[JsonProperty("@event_no")]
public string event_no { get; set; }
[JsonProperty("@name")]
public string name { get; set; }
public Show Show { get; set; }
}
public class Events
{
public List<Event> Event { get; set; }
}
public class EventsData
{
public Events Events { get; set; }
}
However, when I am trying to deserialize I get the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'VM_Models.Show' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
What exactly am I doing wrong? If I make the Show property dynamic
instead of class Show
then it works
UPDATE: I did find in the data sometimes there are more than one shows:
{ "@event_no":"54535", "@name":"REDACTED", "Show": [ { "@show_no": "1", "@show_datetime": "2009-05-06 19:00:00" }, { "@show_no": "2", "@show_datetime": "2009-05-07 19:00:00" }, { "@show_no": "3", "@show_datetime": "2009-05-08 19:00:00" }, { "@show_no": "4", "@show_datetime": "2009-05-09 19:00:00" }, { "@show_no": "5", "@show_datetime": "2009-05-10 19:00:00" } ] }