Search code examples
c#jsondeserializationrestsharpjson-deserialization

Deserialize JSON array into C# Structure with RestSharp


I am dynamically taking different JSON structures into various C# structures, using RestSharp and IRestResponse<T> response = client.Execute<T>(request). But, one particular JSON result is giving me trouble, where it starts and ends with brackets...

My JSON starts and ends with "[" and "]" characters:

[
  {
    "first": "Adam",
    "last": "Buzzo"
  },
  {
    "first": "Jeffrey",
    "last": "Mosier"
  }
]

I've created this class structure:

public class Person
{
    public string first { get; set; }
    public string last { get; set; }
}
public class Persons
{
    public List<Person> person { get; set; }
}

I use RestSharp within a method to deserialize dynamically into my Persons type T...

IRestResponse<T> response = client.Execute<T>(request);
return response;

The problem is that when T is Persons I get this error on the client.Execute line:

Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

I also tried with Json.Net and got this error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Persons' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.

Given the initial "[" character, I tried deserializing into a List of Persons. That stopped the error message and I had the right number of "Person" records BUT they were all null. (I confirmed casing of names was identical.) I also don't really want to use a List collection when there is always only one element to the array from the target server and so binding to "Persons" makes more sense than "List".

What is the correct way to deserialize this JSON into Persons and still within the scope of my dynamic IRestResponse<T> response = client.Execute<T>(request) methodology?


Solution

  • As mentioned in the comments, your json holds an array of persons. Therefore the target structure to deserialize to should match that. Either use:

    var response = client.Execute<List<Person>>(request);
    

    or if you prefer the Persons class, change it to

    public class Persons : List<Person>
    {
    }