![](/img/trans.png)
[英]How I can decode and access Double from JSON using Alamofire and Swift Decode
[英]Getting JSON by using Alamofire and decode - Swift 4
我有一個API,我也想得到請求。
但我嘗試使用JSONDecoder轉換數據類型,但我失敗了。
我不知道如何解碼這個Json像下面的數據。
我想把json [“response”]內容設置為我的User結構。
對我有什么建議嗎? 謝謝。
錯誤域= NSCocoaErrorDomain代碼= 4865“沒有與密鑰ID(”id“)關聯的值。” UserInfo = {NSCodingPath =(),NSDebugDescription =沒有與密鑰ID(“id”)關聯的值。}
這是JSON數據:
{
"status": "success",
"response": {
"id": "1130f1e48b608f79c5f350dd",
"name": "Jack",
},
"errors": ""
}
enum RestfulAPI:String {
case userInfo = "http://www.mocky.io/v2/5a796fb92e00002a009a5a49"
func get(parameters:[String : Any]? = nil,success:@escaping (_ response : Data)->(), failure : @escaping (_ error : Error)->()){
let url = self.rawValue
Alamofire.request(url, method: .get, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response) in
switch response.result {
case .success:
if let data = response.data {
success(data)
}
case .failure(let error):
failure(error)
}
}
}
}
struct User: Decodable {
let id: String
let name: String
}
用法:
RestfulAPI.userInfo.get(success: { data in
do {
let user = try JSONDecoder().decode(User.self, from: data)
print("==) ", user.id, user.name)
}catch let error as NSError{
print(error)
}
}) { (error) in
print(error)
}
密鑰id
不在您期望的級別。 這就是錯誤消息所說的。
密鑰id
和name
位於(子)字典中以進行密鑰response
。
所以你需要一個傘形結構
struct Root : Decodable {
let status: String
let response: User
}
struct User: Decodable {
let id: String
let name: String
}
然后解碼
let root = try JSONDecoder().decode(Root.self, from: data)
let user = root.response
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.