Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestSharp deserialize to List<MyClass>

I use RestSharp to get json from some page. The response is this:

{
    "cars": [
        {
            "name": "car1",
            "size": 10,
            "color": "black"
        },
        {
            "name": "car2",
            "size": 20,
            "color": "white"
        }
    ]
}

I have this class for one car:

public class Car
    {
      public string Name { get; set; }
      public int Size { get; set; }
      public string Color { get; set; }
    }

How can I map this response to the list of cars?

If there is not the "cars":[ in json, it is easy, but now I need to do it like this:

private class Cars
    {
      public List<Car> Cars { get; set; }
    }

    ...

    IRestResponse<Cars> response = client.Execute<Cars>(request);
    ...
    ...response.Data.Cars...

but I feel that the class Cars is useless and I want to do something like this:

IRestResponse<List<Car>> response = client.Execute<List<Car>>(request);
...
...response.Data...

EDIT:

This is for the request creating:

RestClient client = new RestClient(http...));
        RestRequest request = new RestRequest();
like image 930
Banana Cake Avatar asked Aug 16 '18 09:08

Banana Cake


1 Answers

Assuming there is only one 'cars' array, code below will get the job done.

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

//You can access cars this way.
var data = response.Data["cars"];
like image 101
Selçuk Avatar answered Sep 26 '22 13:09

Selçuk