gpt4 book ai didi

ios - 使用 swiftlyJSON 在 Swift 中解析具有未知根元素的 JSON

转载 作者:可可西里 更新时间:2023-11-01 01:06:07 25 4
gpt4 key购买 nike

我在 iOS 中使用 Swift 工作。我正在使用的服务返回以下 JSON(随着节点开始重复而被截断):

    {
"Ambler Departures: April 15, 2015, 2:57 pm": [
{
"Northbound": [
{
"direction": "N",
"path": "R5N",
"train_id": "564",
"origin": "Frazer Yard",
"destination": "Colmar-Link Belt",
"status": "On Time",
"service_type": "LOCAL",
"next_station": "North Broad St",
"sched_time": "Apr 15 2015 03:27:00:000PM",
"depart_time": "Apr 15 2015 03:27:00:000PM",
"track": "2",
"track_change": null,
"platform": " ",
"platform_change": null
},
{
"direction": "N",
"path": "R5N",
"train_id": "6566",
"origin": null,

请注意,根节点是由服务动态创建的——我无法知道它会是什么,因为用户可以选择从五十个车站之一出发,时间是基于网站上的时间服务器,这可能与用户时钟上的时间不一致。

我想从 Northbound 数组中提取数据,然后从 JSON 中较低的 Southbound 数组中提取数据。

我正在获取服务返回的数据,但无法正确解析。我无法通过根节点(动态节点)到达内部结构。

这是我正在尝试的:

let json = JSON(data:data)
var x = 0
while x < json.count
{
let track = json[0]["Northbound"][x]["track"].string
println(track)
x++
}

结果为“nil”。我卡住了……

我知道 json[0] 可能是错误的,因为该级别的 JSON 不是数组。提前致谢

最佳答案

如果 json 是来自 SwiftyJSON 的 JSON 对象,但您知道它是一个具有未知键的字典,您可以通过以下方式找到该键:

let theKey = json.dictionary!.keys.first

然后访问数组:

let theArray = json[theKey] as! [[String:AnyObject]]  // array of dictionaries

那么theArray[0]就是以“Northbound”为键的字典,它包含一个包含信息的字典数组。

(经过编辑以反射(reflect)特定于 SwiftyJSON 的正确答案。)

关于ios - 使用 swiftlyJSON 在 Swift 中解析具有未知根元素的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658747/

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