Search code examples
c#deserializationrestsharp

RestSharp: Unable to deserialize array


I am using RestSharp. I have the following code:

public void MyMethod()
{
       var client = new RestClient("https://test_site/api");
       var request = new RestRequest("/endpoint", Method.GET);

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

My problem is that in all the examples that I have seen, the JSON is in the form "property":"value".

However, in my case I just have an array of strings:

[
  "Str1",
  "Str2",
  "Str3"
]

So I know how to deserialize an object when the JSON is in the form "property":"value", but my question is: how can I deserialize an array of strings?


Solution

  • Note the square bracket rather than curly bracket. The curly brackets represents an object, the square brackets represent an array.

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

    Or

    var response = client.Execute<string[]>(request);
    

    You can also have an array in an object (see colors)

    {
        "name": "iPhone 7 Plus",
        "manufacturer": "Apple",
        "deviceType": "smartphone_tablet",
        "searchKey": "apple_iphone_7_plus",
        "colors": ["red", "blue"]
    }
    

    and the corresponding model would look like this:

    public class MyMapClass 
    {
        public string Name { get; set; }
        public string Manufacturer { get; set; }
        public string DeviceType { get; set; }
        public string SearchKey { get; set; }
        public List<string> Colors { get; set; }
    }