问题描述
所以 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,"available_stalls" : 16,"name" : "Stjørdal,norway"
},{
"location" : {
"lat" : 63.734355000000001,"long" : 11.281487
},"total_stalls" : 12,"distance_miles" : 31.206503999999999,"available_stalls" : 11,"name" : "Levanger,{
"location" : {
"lat" : 62.832030000000003,"long" : 10.009639999999999
},"total_stalls" : 20,"distance_miles" : 44.117753,"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
},{
"distance_miles" : 46.220022999999998,"name" : "Falksenteret","location" : {
"lat" : 63.293301999999997,"long" : 9.0834460000000004
},{
"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
。
解决方法
第一个错误是您使用的 JSON 初始值设定项将创建单个 JSON 字符串对象,它不会将字符串解析为 JSON 数据:
代替:
let json = JSON(nearbyChargingSites.jsonString!)
您需要使用:
let json = JSON(data: dataFromJSONString)
其次,您需要遍历 superchargers 数组以收集所有值
尝试类似:
if let dataFromString = nearbyChargingSites.jsonString!.data(using: .utf8,allowLossyConversion: false) {
let json = try! JSON(data: dataFromString,options: .allowFragments)
for supercharger in json["superchargers"].arrayValue {
let jsonName = supercharger["name"].stringValue
let jsonLat = supercharger["location"]["lat"].doubleValue
let jsonLong = supercharger["location"]["long"].doubleValue
}
}
请注意,上面的代码不会执行错误处理,如果 JSON 中缺少值,则会崩溃。