How to convert json data from alamofire to swift objects

社会主义新天地 提交于 2019-12-06 08:01:17

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.

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

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

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

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