以下是我使用Alamofire调用GETapi以获取火车详细信息的代码:
var url:String!
url = "https://api.railwayapi.com/v2/name-number/train/bhopal/apikey/iixp5yxd/"
Alamofire.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success(let json):
print(json)
if let json = response.result.value as? [String:Any] {
print(json["train"]!)
if let nestedDictionary1 = json["train"] as? [String: AnyObject] {
// access individual value in dictionary
if let views = nestedDictionary1["number"] as? String {
print(views)
}
if let classes = nestedDictionary1["classes"] as? [String: AnyObject] {
print(classes)
}
}
}
DispatchQueue.main.async {
// handle your code
}
case .failure(let error):
print(error)
}
}
在print(json)
行,我收到以下 JSON 响应:
{
debit = 1;
"response_code" = 200;
train = {
classes = (
{
available = N;
code = 2S;
name = "SECOND SEATING";
},
{
available = N;
code = FC;
name = "FIRST CLASS";
},
{
available = Y;
code = 2A;
name = "SECOND AC";
},
{
available = N;
code = 3E;
name = "3rd AC ECONOMY";
},
{
available = Y;
code = SL;
name = "SLEEPER CLASS";
},
{
available = N;
code = CC;
name = "AC CHAIR CAR";
},
{
available = Y;
code = 3A;
name = "THIRD AC";
},
{
available = Y;
code = 1A;
name = "FIRST AC";
}
);
days = (
{
code = MON;
runs = Y;
},
{
code = TUE;
runs = Y;
},
{
code = WED;
runs = Y;
},
{
code = THU;
runs = Y;
},
{
code = FRI;
runs = Y;
},
{
code = SAT;
runs = Y;
},
{
code = SUN;
runs = Y;
}
);
name = "SHAN-E- BHOPAL EXP";
number = 12156;
};
}
我应该如何提取键"类"的值和"类"的相应键。我在上面的代码中使用了它,但不幸的是它不起作用:
if let classes = nestedDictionary1["classes"] as? [String: AnyObject] {
print(classes)
}
由于我是阿拉莫火的新手,请告诉我哪里出错以及如何解决这个问题?
请阅读输出。JSON 只有两种集合类型,数组[]
(在输出()
中(和字典{}
。
所以键classes
的值显然是一个数组([[String:Any]]
(,而JSON未指定的值总是Any
的,而不是AnyObject
的。
并且请使用更具描述性的变量名称。
if let json = response.result.value as? [String:Any] {
if let train = json["train"] as? [String: Any] {
print(train)
// access individual value in dictionary
if let number = train["number"] as? String { // more likely `Int`
print(number)
}
if let classes = train["classes"] as? [[String: Any]] {
for aClass in classes {
let name = aClass["name"] as! String
let available = aClass["available"] as! String
print(name, available)
}
}
}
}
尽管如此,请考虑使用Codable
协议。更方便,更高效