RestSharp反序列化为List <myclass>

时间:2018-08-16 09:25:18

标签: c# .net json rest restsharp

我使用RestSharp从某个页面获取json。响应是这样的:

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

我有一辆汽车上这堂课:

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

我如何将此响应映射到汽车列表?

如果json中没有"cars":[,这很容易,但是现在我需要这样做:

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

    ...

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

但是我觉得Cars类没有用,我想做这样的事情:

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

编辑:

这是用于创建请求的:

RestClient client = new RestClient(http...));
        RestRequest request = new RestRequest();

2 个答案:

答案 0 :(得分:2)

假设只有一个“汽车”阵列,下面的代码将完成工作。

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

//You can access cars this way.
var data = response.Data["cars"];

答案 1 :(得分:0)

我不知道这是否正是您要寻找的东西,但是当我使用json(JSonConvert位于NewtownSoft.Json包中)时,我发现这种方式非常舒适

dynamic dynamicObject = JsonConvert.DeserializeObject(jsonString);
if(dynamicObject.cars != null)
{
    foreach(var car in dynamicObject.cars)
    {
        Car currentCar = new Car();
        If(car.name != null) currentCar.Name= car.name; 
        If(car.size!= null) currentCar.Size= car.size;
        If(car.color!= null) currentCar.Color= car.color;
        myCarList.Add(currentCar);
    }
}

另外,我认为可以通过以下方式用更少的代码来完成:

JObject obj = JsonConvert.DeserializeObject(jsonString);
foreach(var car in obj["cars"])
{
    myCarList.Add(JsonConvert.DeserializeObject(car.toString());
}