我一直试图找出如何将Alamofire的JSON响应的一部分保存为变量来制作if语句,但似乎无法找到如何做到这一点。
我制作了一段代码作为问题的例子,其中包括以下内容:
In [343]: df = pd.DataFrame(np.random.randint(0, 10, (5,3)), columns=list('abc'))
In [344]: add_cols = list('xyz')
In [345]: add_cols
Out[345]: ['x', 'y', 'z']
In [346]: df
Out[346]:
a b c
0 4 9 0
1 1 1 1
2 8 8 1
3 0 1 4
4 8 5 6
In [347]: df[add_cols] = pd.DataFrame(0, index=df.index, columns=add_cols)
In [348]: df
Out[348]:
a b c x y z
0 4 9 0 0 0 0
1 1 1 1 0 0 0
2 8 8 1 0 0 0
3 0 1 4 0 0 0
4 8 5 6 0 0 0
我从API请求中得到以下响应:
import UIKit
import Alamofire
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Alamofire.request("http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=44143256ee15e9c3f521ca062463dd8d").responseJSON { response in
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
}
根据这个JSON响应,我想保存天气描述,以便我可以使用以下语句:
JSON: {
base = stations;
clouds = {
all = 0;
};
cod = 200;
coord = {
lat = "51.51";
lon = "-0.13";
};
dt = 1485031800;
id = 2643743;
main = {
humidity = 83;
pressure = 1026;
temp = "270.54";
"temp_max" = "273.15";
"temp_min" = "267.15";
};
name = London;
sys = {
country = GB;
id = 5091;
message = "0.0038";
sunrise = 1484985141;
sunset = 1485016345;
type = 1;
};
visibility = 7000;
weather = (
{
description = haze;
icon = 50n;
id = 721;
main = Haze;
}
);
wind = {
speed = 1;
};
}
如果有人能帮助我,我会非常感激!如果我必须使用SwiftyJSON来让它变得更加简单,那我就一直在努力解决这个问题,并且需要弄清楚它!
答案 0 :(得分:0)
您可以在打印出JSON响应后解析结果:
guard let JSON = response.result.value as? [String:Any],
let weather = JSON["weather"] as? [[String:Any]] else {
print("Could not parse weather values")
return
}
for element in weather {
if let description = element["description"] as? String {
print(description)
}
}
如果你想保存结果,或根据你所描述的某种结果做某事,你可以插入别的东西,而不仅仅是print(description)
:
if description == "sunny" {
//do something
}
如果这是有道理的,请告诉我。请注意,Xcode控制台中的(
和)
表示“数组”。