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

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

我上了一辆车的此类类(class):
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...

但我觉得汽车课没用,我想做这样的事情:
IRestResponse<List<Car>> response = client.Execute<List<Car>>(request);
...
...response.Data...

编辑:

这是用于创建请求的:
RestClient client = new RestClient(http...));
        RestRequest request = new RestRequest();

最佳答案

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

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

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

关于c# - RestSharp反序列化为List <MyClass>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51873728/

10-12 17:52