如何将JSON数据从Alamofire转换为Swift对象 [英] How to convert json data from alamofire to swift objects

查看:354
本文介绍了如何将JSON数据从Alamofire转换为Swift对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在
xcode 6.2中使用swift 1.1快速制作照片查看器应用程序

hi there im making a photo viewer app in swift using swift 1.1 in xcode 6.2

我遇到了麻烦尝试将json响应从
alamofire转换为swift对象。我使用了swiftyjson库,但似乎
存在兼容性问题。这是我的模型类

i am a having trouble trying to convert json response from alamofire to swift objects.i have used swiftyjson library but it seems there is a compatibility issues.here is my model class



import Foundation

struct Photo {

    var name: String
    var filename :String
    var notes: String
}




这是我的viewController

here is my viewController



    import UIKit

    class ImageViewerTableViewController: UITableViewController {
    var photos = [Photo]()

        override func viewDidLoad() {
            super.viewDidLoad()

Alamofire.request(.GET, "http://httpbin.org/get")
         .responseJSON { (_, _, JSON, _) in

         }

      }

在这种情况下,我如何将json映射为快速对象

how can i map json to swift objects in this situation

谢谢。

推荐答案

最好的解决方案是使用 AlamofireObjectMapper

The best solution is to use AlamofireObjectMapper.

您的代码应该看起来像这样:

Your code should look like this:

import Foundation
import ObjectMapper

struct Photo: Mappable {
    var name: String
    var filename :String
    var notes: String

    required init?(map: Map) {}

    func mapping(map: Map) {
        self.name     <- map["name"]
        self.filename <- map["filename"]
        self. notes   <- map["notes"]
    }
}

在viewController:

In viewController:

import UIKit

class ImageViewerTableViewController: UITableViewController {
    var photos = [Photo]()

    override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire
            .request(.GET, "http://httpbin.org/get")
            .responseArray { (response: Response<[Photo], NSError>) in
            if let myPhotos = response.result.value {
                print(myPhotos)
            }
        }
    }
}

AlamofireObjectMapper ObjectMapper 的文档以获取更多信息。

Look the documentation of AlamofireObjectMapper and ObjectMapper for more informations.

这篇关于如何将JSON数据从Alamofire转换为Swift对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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