问题
I have an API and I also want to get request.
But I try to using JSONDecoder to convert data type and I failed.
I don't know how to decode this Json like following data.
I want to take json["response"] contents setting my User struct.
Have any suggestion to me?
Thanks.
Error Domain=NSCocoaErrorDomain Code=4865 "No value associated with key id ("id")." UserInfo={NSCodingPath=( ), NSDebugDescription=No value associated with key id ("id").}
This is JSON Data:
{
"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
}
usage:
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)
}
回答1:
The key id
is not on the level where you expect it. That's what the error message states.
The keys id
and name
are in the (sub)dictionary for key response
.
So you need an umbrella struct
struct Root : Decodable {
let status: String
let response: User
}
struct User: Decodable {
let id: String
let name: String
}
Then decode
let root = try JSONDecoder().decode(Root.self, from: data)
let user = root.response
来源:https://stackoverflow.com/questions/48639299/getting-json-by-using-alamofire-and-decode-swift-4