How to convert json data from alamofire to swift objects

14,297

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

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

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

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

Share:
14,297

Related videos on Youtube

user2431114
Author by

user2431114

Updated on September 15, 2022

Comments

  • user2431114
    user2431114 about 1 year

    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 .

  • Edwin Vermeer
    Edwin Vermeer over 8 years
    I now also have an Alamofire extension for this. See github.com/evermeer/AlamofireJsonToObjects