[英]How to access a nested dictionaries from API
Let's say that I want to access an nest dictionary response from API like this format: 假设我想从API像以下格式访问嵌套字典响应:
(
{
"active_upcoming_bookings" = (
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-23T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 75;
"desk_name" = D2;
"desk_type" = Standing;
id = 299;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 11;
wing = Right;
},
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-23T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 74;
"desk_name" = D3;
"desk_type" = Standing;
id = 300;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 12;
wing = Right;
},
{
"booked_from" = "2018-03-01T00:00:00.000+08:00";
"booked_to" = "2018-03-01T23:59:59.999+08:00";
"creator_id" = 1;
"desk_id" = 76;
"desk_name" = D1;
"desk_type" = Standing;
id = 298;
"project_id" = 8;
"project_name" = "expo 2017";
status = Upcoming;
"user_id" = 16;
wing = Right;
}
);
project = {
"created_at" = "2017-05-31T16:29:06.012+08:00";
"created_by_id" = 1;
"end_date" = "2018-03-23T23:59:59.999+08:00";
id = 8;
name = "expo 2017";
"start_date" = "2018-03-01T00:00:00.000+08:00";
"updated_at" = "2017-05-31T16:29:06.012+08:00";
};
}
)
My code for access the nested dictionary: 我访问嵌套字典的代码:
let response = responseJSON as! [String: [String: Any]]]()
let projectId = response["project"]?["id"] as Int
let projectName = response["project"]?["name"] as String
but it pops up subscript error in compiler. 但它会在编译器中弹出下标错误。
What kind of data model should I use for access this? 我应该使用哪种数据模型进行访问?
Your JSON
response is Array
not Dictionary
and active_upcoming_bookings
array and project
dictionary is within the first dictionary of your response Array. 您的
JSON
响应不是Array
而是Dictionary
而active_upcoming_bookings
数组和project
字典在响应数组的第一个字典内。
if let response = responseJSON as? [[String:Any]], let dictionary = response.first,
let projectDic = dictionary["project"] as? [String:Any] {
//Now subscript with projectDic to access id and name
let projectId = projectDic["id"] as? Int
let projectName = projectDic["name"] as? String
}
Try this 尝试这个
let mainDict = arrResponse[0] as! [String : Any]
let projectDict = mainDict["project"] as! [String : Any]
let strProjectID = projectDict["id"] as! Int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.