SwiftyJSON 解析 json 查询
SwiftyJSON parse json query
我正在 swift 3 中编写代码,用于解析来自 http 请求的 json 格式的查询结果。
json格式为:
JSON: {
base = stations;
coord = {
lat = "23.9";
lon = "42.89";
};
weather = (
{
description = mist;
icon = 50n;
id = 701;
main = Mist;
},
{
description = fog;
icon = 50n;
id = 741;
main = Fog;
}
);
wind = {
deg = "222.506";
speed = "1.72";
};}
我的代码是:
Alamofire.request(url).responseJSON { response in
if let a = response.result.value {
let jsonVar = JSON(a)
if let resDati = jsonVar["base"].string {
print(resDati as String) // <- OK
}
if let dati2 = jsonVar["weather"].array {
for item in dati2 {
print(" > \(item["main"])") // <- OK
}
}
} else {
print(Error.self)
}
}
问题出在 "coord" 和 "wind" 我试过的数据上:
if let dati4 = jsonVar["wind"].array {
for item in dati4 {
print("-- \(item)")
} }
我无法以 json 格式打印与 "wind" 和 "coord" 相关的数据。
我该如何解决这个问题。
谢谢。
键 wind
包含一个字典,而不是一个数组,您可以通过以下代码使用 SwiftyJSON 获取 deg
和 speed
值:
if let wind = jsonVar["wind"].dictionary,
let deg = wind["deg"]?.double,
let speed = wind["speed"]?.double {
print(deg, speed)
}
coord
相应工作
if let coord = jsonVar["coord"].dictionary,
let lat = coord["lat"]?.double,
let lon = coord["lon"]?.double {
print(lat, lon)
}
注意:所有值都是 Double
类型,json 格式 具有误导性。
我正在 swift 3 中编写代码,用于解析来自 http 请求的 json 格式的查询结果。
json格式为:
JSON: {
base = stations;
coord = {
lat = "23.9";
lon = "42.89";
};
weather = (
{
description = mist;
icon = 50n;
id = 701;
main = Mist;
},
{
description = fog;
icon = 50n;
id = 741;
main = Fog;
}
);
wind = {
deg = "222.506";
speed = "1.72";
};}
我的代码是:
Alamofire.request(url).responseJSON { response in
if let a = response.result.value {
let jsonVar = JSON(a)
if let resDati = jsonVar["base"].string {
print(resDati as String) // <- OK
}
if let dati2 = jsonVar["weather"].array {
for item in dati2 {
print(" > \(item["main"])") // <- OK
}
}
} else {
print(Error.self)
}
}
问题出在 "coord" 和 "wind" 我试过的数据上:
if let dati4 = jsonVar["wind"].array {
for item in dati4 {
print("-- \(item)")
} }
我无法以 json 格式打印与 "wind" 和 "coord" 相关的数据。
我该如何解决这个问题。
谢谢。
键 wind
包含一个字典,而不是一个数组,您可以通过以下代码使用 SwiftyJSON 获取 deg
和 speed
值:
if let wind = jsonVar["wind"].dictionary,
let deg = wind["deg"]?.double,
let speed = wind["speed"]?.double {
print(deg, speed)
}
coord
相应工作
if let coord = jsonVar["coord"].dictionary,
let lat = coord["lat"]?.double,
let lon = coord["lon"]?.double {
print(lat, lon)
}
注意:所有值都是 Double
类型,json 格式 具有误导性。