gpt4 book ai didi

c# - C# 中对象(带数组)的 API

转载 作者:行者123 更新时间:2023-11-30 23:18:55 25 4
gpt4 key购买 nike

我正在从 transportapi.com 返回数据并将其加载到对象中,但未包含 json 数组中的数据。

返回的json是:

{
"atcocode": "490012745J",
"smscode": "47889",
"request_time": "2016-11-11T22:10:42+00:00",
"departures": {
"55": [
{
"mode": "bus",
"line": "55",
"line_name": "55",
"direction": "Bakers Arms",
"operator": "TFL",
"date": null,
"expected_departure_date": "2016-11-11",
"aimed_departure_time": null,
"expected_departure_time": "22:19",
"best_departure_estimate": "22:19",
"source": "Countdown instant"
}
]
}
}

Controller 代码:

var source = "http://transportapi.com/v3/uk/bus/stop/490012745J/live.json?api_key=[key]&app_id=[appid]";

Uri sourceUri = new Uri(source);
System.Net.Http.HttpClient sourceClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage sourceResponse = await sourceClient.GetAsync(sourceUri);
var sourceArray = await sourceResponse.Content.ReadAsStringAsync();

var selections = JsonConvert.DeserializeObject<RootObject>(sourceArray);

模型类:

public class BusDepartures
{
public string mode { get; set; }
public string line { get; set; }
public string line_name { get; set; }
public string direction { get; set; }
public string busoperator { get; set; }
public object date { get; set; }
public string expected_departure_date { get; set; }
public object aimed_departure_time { get; set; }
public string expected_departure_time { get; set; }
public string best_departure_estimate { get; set; }
public string source { get; set; }
}

public class Departures
{
// First attempt, use BusDepartures object.
//public List<BusDepartures> BusDepartures { get; set; }

// Second attempt (as "55" is an array), use array, then convert to object later.
public string[] routes { get; set; }
}

public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public Departures departures { get; set; }
}

在 Departures 类中,我确实尝试创建一个 BusDepartures 对象来存储出发的详细信息,但我想知道,因为它是一个数组,我是否应该改用 routes 数组?但是,在单步执行代码时,BusDepartures 对象(未注释时)和路由数组均为空。

有什么想法吗?我错过了什么?

更新:

感谢 botond.botos 的回答。我将类(class)修改为

public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public IDictionary<int, IEnumerable<BusDepartures>> departures { get; set; }
}

它奏效了。

最佳答案

您不需要 Departures 类,并尝试按以下方式更改 RootObject 类:

public class RootObject
{
public string atcocode { get; set; }
public string smscode { get; set; }
public string request_time { get; set; }
public IDictionary<int, IEnumerable<BusDepartures>> departures { get; set; }
}

关于c# - C# 中对象(带数组)的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40557815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com