将json集合响应映射到swift对象类的简单方法

时间:2015-04-26 23:24:11

标签: json swift alamofire

我尝试了很多库,Alamofire,JsonHelper,ObjectMapper等......但不幸的是,我已经将json集合响应映射到了一个对象类。 我开发了一个带有swift 1.2和xcode 6.3的IOS 8应用程序,我的模型有两类:

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] = []

}

我有另一个类要求我的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)
                }
            }
        }
    }
}

我认为,有一种简单的方法可以在swift中映射对象。我想知道,我如何将completionHandler(数据)转换为[Club]对象?

让数据 = jsonObj ["点击"]。arrayValue为[JSON]?的

[{
  "_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"
  }
}]

2 个答案:

答案 0 :(得分:0)

对于objective-c try JSONModel,它可能就是你要找的...... 和here你可以找到更多使用它的例子

请注意swift(来自JSONModel' GitHub页面):

  

Swift在幕后以不同的方式工作,而不是Objective-C。因此,我找不到在Swift中重新创建JSONModel的方法。 Objective-C中的JSONModel通过CocoaPods或作为导入的Objective-C库在Swift应用程序中运行。

<强>更新

查看Apple发布的关于 在Swift中使用JSON 的博客文章 https://developer.apple.com/swift/blog/?id=37

答案 1 :(得分:0)

使用Swift 2.0,现在可以简单地将json复制到http://www.json4swift.com,并且将自动生成具有整个键值映射的swift模型,您需要做的就是通过传递任一数组来实例化模型或者你的Json字典。