Ban*_*ake 5 .net c# rest json restsharp
我使用 RestSharp 从某个页面获取 json。回应是这样的:
{
"cars": [
{
"name": "car1",
"size": 10,
"color": "black"
},
{
"name": "car2",
"size": 20,
"color": "white"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我有一辆车的这个类:
public class Car
{
public string Name { get; set; }
public int Size { get; set; }
public string Color { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何将此响应映射到汽车列表?
如果没有"cars":[在 json 中,这很容易,但现在我需要这样做:
private class Cars
{
public List<Car> Cars { get; set; }
}
...
IRestResponse<Cars> response = client.Execute<Cars>(request);
...
...response.Data.Cars...
Run Code Online (Sandbox Code Playgroud)
但我觉得 Cars 类没用,我想做这样的事情:
IRestResponse<List<Car>> response = client.Execute<List<Car>>(request);
...
...response.Data...
Run Code Online (Sandbox Code Playgroud)
编辑:
这是用于创建请求:
RestClient client = new RestClient(http...));
RestRequest request = new RestRequest();
Run Code Online (Sandbox Code Playgroud)
假设只有一个 'cars' 数组,下面的代码将完成这项工作。
var response = client.Execute<Dictionary<string,List<Car>>>(request);
//You can access cars this way.
var data = response.Data["cars"];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4343 次 |
| 最近记录: |