simple way to map a json collection response into swift object class

走远了吗. 提交于 2019-12-11 03:54:50

问题


Ive tried a lot of libraries, Alamofire, JsonHelper, ObjectMapper etc..., but unfortunately, Ive coundn't map a json collection response into an object class. Im developing an IOS 8 App with swift 1.2 and xcode 6.3, and two classes of my model are:

Club.swift

class Club { 

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}

Location.swift

class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}

I have another class to request to my API:

apliClient.swift

class ApiClient {

    var clubs = [Club]?()


    func getList(completionHandler: ([JSON]) -> ()) {
        let URL = NSURL(string: "https://api.com/v1/clubs")
        let mutableURLRequest = NSMutableURLRequest(URL: URL!)

        mutableURLRequest.setValue("Content-Type", forHTTPHeaderField: "application/json")
        mutableURLRequest.HTTPMethod = "GET"
        mutableURLRequest.setValue("Bearer R01.iNsG3xjv/r1LDkhkGOANPv53xqUFDkPM0en5LIDxx875fBjdUZLn1jtUlKVJqVjsNwDe1Oqu2WuzjpaYbiWWhw==", forHTTPHeaderField: "Authorization")

        let manager = Alamofire.Manager.sharedInstance
        let request = manager.request(mutableURLRequest)

        request.responseJSON { (request, response, json , error) in
            if (json != nil){
                var jsonObj = JSON(json!)
                if let data = jsonObj["hits"].arrayValue as [JSON]?{
                    completionHandler(data)
                }
            }
        }
    }
}

and I think, there is a simple way to mapping objects in swift. I would like to know, how I can return the completionHandler(data) converted into a [Club] object?

let data = jsonObj["hits"].arrayValue as [JSON]? is

[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

回答1:


You can do this with the ObjectMapper library that you mentioned above. Simply create the Club class and make sure it implements the Mappable protocol. Then you can use ObjectMapper as follows to map the data:

let clubs = Mapper<Club>().mapArray(JSONString)

Full disclosure: I am the author of ObjectMapper.




回答2:


With Swift 2.0, it is now possible, simple copy your json to http://www.json4swift.com and the swift models with entire key-value mapping will be auto generated, all you need to do is instantiate the models by passing either array or dictionary out of your Json.




回答3:


For objective-c try JSONModel it can be what you are looking for... and here you can find some more example of using it

note this about swift (from JSONModel's GitHub page):

Swift works in a different way under the hood than Objective-C. Therefore I can't find a way to re-create JSONModel in Swift. JSONModel in Objective-C works in Swift apps through CocoaPods or as an imported Objective-C library.


Update:

Check ups this blog post from apple about Working with JSON in Swift https://developer.apple.com/swift/blog/?id=37



来源:https://stackoverflow.com/questions/29884827/simple-way-to-map-a-json-collection-response-into-swift-object-class

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