Search code examples
c#jsonjson.netjson-deserialization

How to deserialize a (sometimes) encapsulated JSON array in C#


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:

  1. Have the first layer unwrapped if the answer happens to not be an array
  2. Setup the name "data" as an optional name for the array

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; }
}

Solution

  • 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; }
    }