使用Alamofire和解码获取JSON-Swift 4 [英] Getting JSON by using Alamofire and decode - Swift 4

查看:121
本文介绍了使用Alamofire和解码获取JSON-Swift 4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,我也想获取请求。

但是我尝试使用JSONDecoder转换数据类型,但失败了。

我不知道如何像下面的数据一样解码此Json。

我想获取设置我的用户结构的 json [ response] 内容。

对我有什么建议吗?
谢谢。

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.


错误域= NSCocoaErrorDomain代码= 4865没有与键id( id)关联的值。 UserInfo = {NSCodingPath =(
),NSDebugDescription =没有与键id( id)关联的值。}

Error Domain=NSCocoaErrorDomain Code=4865 "No value associated with key id ("id")." UserInfo={NSCodingPath=( ), NSDebugDescription=No value associated with key id ("id").}

这是JSON数据:

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
}

用法:

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 在(sub )的键响应的字典。

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
}

然后解码

let root = try JSONDecoder().decode(Root.self, from: data)
let user = root.response

这篇关于使用Alamofire和解码获取JSON-Swift 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆