2017-05-31 52 views
-1

比方說,我要訪問的API類似這樣的格式的窩詞典響應:如何從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"; 
    }; 
} 
) 

我對訪問代碼嵌套詞典:

let response = responseJSON as! [String: [String: Any]]]() 

let projectId = response["project"]?["id"] as Int 
let projectName = response["project"]?["name"] as String 

但它會在編譯器中彈出下標錯誤。

我應該使用什麼樣的數據模型來訪問它?

回答

1

JSON響應ArrayDictionaryactive_upcoming_bookings陣列和project字典是你的反應Array的第一個字典中。

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 
} 
+0

的感謝!我現在試一試 – aznelite89

+0

如果我已經從api接收多個項目,因爲這是爲了檢索第一個響應,該怎麼辦? – aznelite89

+1

@ aznelite89是的,那麼你需要簡單地遍歷響應數組,並且需要訪問每個字典以從中獲得項目字典,對於'active_upcoming_bookings'數組也是如此。 –

1

試試這個

let mainDict = arrResponse[0] as! [String : Any] 
let projectDict = mainDict["project"] as! [String : Any] 
let strProjectID = projectDict["id"] as! Int