【发布时间】:2020-12-08 09:25:37
【问题描述】:
在 Swift 中解析来自 AF 请求的以下响应 – let json = result as! NSDictionary – 我非常迷茫:
{
errors = (
);
get = statistics;
parameters = {
country = germany;
};
response = (
{
cases = {
"1M_pop" = 14303;
active = 317167;
critical = 4179;
new = "+15161";
recovered = 863300;
total = 1200006;
};
continent = Europe;
country = Germany;
day = "2020-12-08";
deaths = {
"1M_pop" = 233;
new = "+380";
total = 19539;
};
population = 83900328;
tests = {
"1M_pop" = 347331;
total = 29141172;
};
time = "2020-12-08T09:15:08+00:00";
}
);
results = 1;
}
知道如何获取实际案例编号,例如new 案例的数量吗?
到目前为止,我已经尝试了以下(错误抛出)方法:
if let responseDict = result as? NSDictionary {
if let data = responseDict.value(forKey: "response") as?
[NSDictionary] {
// Get case numbers
guard let cases = data[0]["cases"] else { return }
guard let casesPerOneMil = cases[0] as! Int else { return }
print(casesPerOneMil)
}
}
【问题讨论】:
-
有什么尝试吗?你知道字典和数组是如何工作的吗?如何使用键访问字典的值?如果是,JSON 只是 Dictionary、Array、String、Numbers(和 null)。所以从
let response = json["response"]开始(这是一个响应数组)。等等。但是,Codable可能是一个好主意。 -
对不起 - 已经包含了我迄今为止在问题中尝试过的内容!
-
要调试,你需要知道
casesnil?casesPerOneNil是零吗?甚至抛出一个错误来崩溃(我不会使用as!,而是as?),如果是这样,错误信息是什么?但显然cases是Dictionary而不是数组。所以cases[0]应该会崩溃并在控制台中给出预期的错误消息。它应该是cases["1M_pop"]。 -
guard let casesPerOneMil = cases["1M_pop"] as! Int else { return }返回Value of type 'Any' has no subscripts
标签: swift alamofire nsdictionary swifty-json