2017-04-06 67 views
-2

我知道很多人都這樣問。我已經在尋找,但不符合我的問題。如何從API中解析JSON

奧凱我會盡我的代碼解釋

我有數據API像這樣

["profile": { 
accountId = 58e470a0c50472851060d083; 
androidDeviceId = "[\"3453247ddcf3f809\"]"; 
androidVersion = 21; 
appId =  (
    "c46b4c10-62ce-11e6-bdd4-59e4df4b8410", 
    "fac915f0-fe2b-11e6-9dfb-55339bd7be35" 
); 
appVersion = "v5.1.0"; 
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg"; 
birthDate = "12/03/1994"; 
"channel-group" = android; 
communityId = 553e09b251906884443eff85; 
coordinates =  { 
    coordinates =   (
     "106.9602383333333", 
     "-6.249333333333334" 
    ); 
    type = Point; 
}; 
crop = ""; 
crops = "<null>"; 
customerId = 5369bd85cae84d0e03246a7c; 
dateSubmitted =  { 
    iso = "2017-04-05T04:20:48.483Z"; 
    timestamp = 1491366048; 
}; 
fullName = "Megi Fernanda"; 
gender = "Laki-laki"; 
homeAddress = Payakumbuah; 
location = "Kota Payakumbuh"; 
moderation =  { 
    at =   { 
     iso = "2017-04-05T04:20:48.483Z"; 
     timestamp = 1491366048; 
    }; 
    by = auto; 
    status = moderated; 
}; 

skill = "Budidaya pertanian"; 
state = "Sumatera Barat"; 
storeType = ""; 
subdistrict = "Payakumbuh Barat"; 
totalConversations =  { 
    articles = 0; 
    forums = 0; 
    questions = 2; 
    responses = 0; 
    storeItems = 1; 
}; 
type = users; 
university = "Politeknik Negeri Pertanian Payakumbuh"; 
}, "accessToken": { 
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0."; 
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo."; 
}] 

我已經可以得到全名,ADDRES,技能狀態等

if let profile = json["profile"] as? NSDictionary { 
     let name = profile["fullName"] 
     let alamat = profile["Skill"] 
} 

但我不知道如何在totalConversation like 問題,storeItems,點

skill = "Budidaya pertanian"; 
state = "Sumatera Barat"; 
storeType = ""; 
subdistrict = "Payakumbuh Barat"; 
totalConversations =  { 
    articles = 0; 
    forums = 0; 
    questions = 2; 
    responses = 0; 
    storeItems = 1; 
}; 

我試圖像

設輪廓= JSON [ 「輪廓」] [ 「totalConversation」]作爲? NSDictionary

error sign:Type'any?'沒有下標成員

+1

Dupe。搜索「類型」任何?沒有下標成員「,這裏出現了超過150次的點擊。 – Ssswift

回答

0

你得到了那個錯誤,因爲json["profile"]Any類型,它沒有任何subscript。因此,您需要將json["profile"]投射到字典中,[String: Any]是Swift中的字典類型。

if let profile = json["profile"] as? [String: Any] { 
    if let totalConversations = profile["totalConversations"] as? [String: Any] { 
     let questions = totalConversations["questions"] as? Int 
    } 
} 
+0

yaaap這是工作。我已經嘗試過 –