通过数组索引解码Alamofire

时间:2018-06-19 05:55:47

标签: json swift alamofire decodable

我有解码json的问题,我不能在struct上使用'self'函数,因为我从服务器获取json的1个键(名称为“my_profile”)和许多值,我通过索引返回,我想将它解码为结构,请帮助我

Alamofire.request(mainUrl, method:.post , parameters: paramstring , encoding: JSONEncoding.default, headers: nil).responseJSON {
    response in
    if let data = response.data
    {
        switch response.result
        {
        case.failure(let error):
            print(error)
        case.success(let value):
            let json=JSON(value)
            guard let dataarr = json["my_profile"].array else { return }
            // I wan't send it to the structure , and get it from another view controllers
            var name = dataarr[0]
            var last_name = dataarr[1]
            var email = dataarr[2]

        }
    }
}

这是我的结构

struct UserInfo : Decodable {

    var name : String 
    var last_name : String
    var emai : String

    }

Json结构:

enter image description here

1 个答案:

答案 0 :(得分:0)

最好为struct

编写初始化程序
struct UserInfo : Decodable {
    var name : String
    var last_name : String
    var email : String

    init(name: String, lastName: String, email: String) {
        self.name = name
        self.last_name = lastName
        self.email = email
    }
}

然后你可以使用这样的东西(根据你的特定需要调整它):

let json = JSON(value)
guard let dataarr = json["my_profile"].arrayValue else { return }
let stringArray = dataarr.map { $0.stringValue }

var name = stringArray[0]
var last_name = stringArray[1]
var email = stringArray[2]

let userInfo = UserInfo(name: name, lastName: last_name, email: email)
// use `userInfo` object

要将对象传递给新的视图控制器,您应该在NewViewController中定义一个变量来存储userInfo对象:

let userInfo: UserInfo!

然后从上面的代码中你应该在最后调用这些行(它使用故事板):

// ...
let userInfo = UserInfo(name: name, lastName: last_name, email: email)

let controller = storyboard?.instantiateViewController(withIdentifier: "NewViewController") as! NewViewController
controller.userInfo = userInfo
present(controller, animated: true, completion: nil)

当您显示NewViewController对象内容时,userInfo是新控制器的位置。不要忘记在故事板中将新视图控制器标识符设置为NewViewController