【发布时间】:2021-09-29 04:41:33
【问题描述】:
所以 JSON 变量 let json = JSON(nearbyChargingSites.jsonString!) 包含当前数据。:
{
"timestamp" : 1626902257093,
"superchargers" : [
{
"location" : {
"lat" : 63.325319,
"long" : 10.305137
},
"total_stalls" : 19,
"distance_miles" : 10.064082000000001,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 15,
"name" : "Leinstrand, Norway - Klett"
},
{
"location" : {
"lat" : 63.466445999999998,
"long" : 10.91766
},
"total_stalls" : 16,
"distance_miles" : 11.838984999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 16,
"name" : "Stjørdal, Norway"
},
{
"location" : {
"lat" : 63.734355000000001,
"long" : 11.281487
},
"total_stalls" : 12,
"distance_miles" : 31.206503999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 11,
"name" : "Levanger, Norway"
},
{
"location" : {
"lat" : 62.832030000000003,
"long" : 10.009639999999999
},
"total_stalls" : 20,
"distance_miles" : 44.117753,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 17,
"name" : "Berkåk, Norway"
}
],
"congestion_sync_time_utc_secs" : 1626902199,
"destination_charging" : [
{
"distance_miles" : 23.366278999999999,
"name" : "Bårdshaug Herregård",
"location" : {
"lat" : 63.299208,
"long" : 9.8448650000000004
},
"type" : "destination"
},
{
"distance_miles" : 38.390034,
"name" : "Fosen Fjordhotel",
"location" : {
"lat" : 63.959356999999997,
"long" : 10.223908
},
"type" : "destination"
},
{
"distance_miles" : 46.220022999999998,
"name" : "Falksenteret",
"location" : {
"lat" : 63.293301999999997,
"long" : 9.0834460000000004
},
"type" : "destination"
},
{
"distance_miles" : 54.981445000000001,
"name" : "Væktarstua",
"location" : {
"lat" : 62.908683000000003,
"long" : 11.893306000000001
},
"type" : "destination"
}
]
}
我使用SwiftyJSON 并尝试获取增压器的纬度、经度和名称,如下所示:
let jsonName = json["superchargers"]["name"]
let jsonLat = json["superchargers"]["location"]["lat"]
let jsonLong = json["superchargers"]["location"]["long"]
当尝试打印其中任何一个时,它们都返回nil。
任何想法我做错了什么,以及如何做到这一点?
我想这样做是因为我想将它们作为annotation 添加到MKMapView。
【问题讨论】:
-
superchargers 是一个数组而不是字典
-
@JoakimDanielson 嗯,那么如何从数组中获取值?增压器数组和位置是字典吗?
-
我不知道 swiftyjson 但我认为你需要某种循环,是的 location 是字典。查看文档以了解如何使用 swiftyjson 循环。
-
使你的结构符合
Codable应该就足够了。不知道为什么在 2021 年需要第三方框架。 -
@Adrian 你会建议我使用
JSONDecoder吗?
标签: ios json swift xcode swifty-json