I’m trying to deserialize the following JSON response:
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]
A problem arises, however, in the fact that the number of parameters following “category” can vary from 0 to 10. Meaning all the following are possible JSON responses:
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Bad", "1":"OK", "2":"Good", "3":"Very good"} … ]
I’m deserializing responses to objects of the following form:
class Poll
{
public int pollid { get; set; }
public string question { get; set; }
public DateTime start { get; set; }
public DateTime end { get; set; }
public string category { get; set; }
[JsonProperty("0")]
public string polloption0 { get; set; }
[JsonProperty("1")]
public string polloption1 { get; set; }
[JsonProperty("2")]
public string polloption2 { get; set; }
[JsonProperty("3")]
public string polloption3 { get; set; }
[JsonProperty("4")]
public string polloption4 { get; set; }
[JsonProperty("5")]
public string polloption5 { get; set; }
[JsonProperty("6")]
public string polloption6 { get; set; }
[JsonProperty("7")]
public string polloption7 { get; set; }
[JsonProperty("8")]
public string polloption8 { get; set; }
[JsonProperty("9")]
public string polloption9 { get; set; }
}
My questions is: Is there perhaps a better way to handle the storing of a varying number of parameters? Having 10 class properties which may or may not be used (depending on the response) seems like such a “hack”.
Any help would be truly appreciated!
Many thanks,
Ted
You can either hold the variable number of properties in and Array
Have something like
where you put all of polloption1, polloption2 …
Or you could deserialize the json to a dynamic type
And access the properties which you know exist