How to convert json data from alamofire to swift objects

微笑、不失礼 提交于 2019-12-10 10:39:08

问题


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

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
}

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

         }

      }

how can i map json to swift objects in this situation

thanks .


回答1:


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"]
    }
}

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)
            }
        }
    }
}

Look the documentation of AlamofireObjectMapper and ObjectMapper for more informations.




回答2:


You can use dataUsingEncoding method, and get your name,filenameandnotes variables from json object, and for parsing json object i recommend SwiftyJSON

Alamofire.request(.GET, "http://httpbin.org/get", parameters: nil, encoding: .URL).responseString(completionHandler: {
        (request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in

        // Convert the response to NSData to handle with SwiftyJSON
        if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
            let json = JSON(data: data)
            println(json)
        }
})



回答3:


You could use EVReflection for that. You can use code like:

var photo:Photo = Photo(json:jsonString)

or

var jsonString:String = photo.toJsonString()

You only have to set your base object to EVObject.

See the GitHub page for more detailed sample code (including array's).




回答4:


If you don't want to write the mapping function, I recommend you to take a look at HandyJSON. A code example:

struct Animal: HandyJSON {
    var name: String?
    var id: String?
    var num: Int?
}

let jsonString = "{\"name\":\"cat\",\"id\":\"12345\",\"num\":180}"

if let animal = JSONDeserializer.deserializeFrom(json: jsonString) {
    print(animal)
}

As it says:

The most significant feature of HandyJSON is that it does not require the objects inherit from NSObject(not using KVC but reflection), neither implements a 'mapping' function(use pointer to achieve property assignment).



来源:https://stackoverflow.com/questions/30838752/how-to-convert-json-data-from-alamofire-to-swift-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!