I'm working with an API that gets sometimes called with slightly malformed data. I'm expecting an array. When there is one or more element in the array, the JSON is well formed:
[
{
"id": 324,
"name": "John Doe"
},
{
"id": 123,
"name": "Jane Doe"
}
]
However, for whatever reason I sometimes get calls with an object containing the empty array, and that array has a name:
{ "data": [] }
Is there a way I can:
Some of the code:
JsonConvert.DeserializeObject<Person[]>(x.Result);
//...
public Person
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "name")]
public int Name {get; set; }
}
you can use something like this
var jToken = JToken.Parse(json);
Datum data = new Datum
{
Data = jToken.Type != JTokenType.Array ? new List<Person>() // or null ??
: jToken.ToObject<List<Person>>()
};
// or just
List<Person> persons = jToken.Type != JTokenType.Array ? new List<Person>()
: jToken.ToObject<List<Person>>();
public class Datum
{
[JsonProperty("data")]
public List<Person> Data { get; set; }
}
public class Person
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}