将json响应映射到自定义对象

时间:2017-06-01 16:16:51

标签: ios swift swifty-json

我收到服务器的以下回复。

 [
    {
      "resourceEmail" : "",
      "kind" : "admin#directory#resources#calendars#CalendarResource",
      "resourceId" : "",
      "resourceName" : "Inubation-Newton-4p",
      "resourceType" : "Confroom",
      "etags" : "\"eqO3c9wtJJ4wVWz2xe0E9HiU_D0\/rfmk2kZmhGi4HcHadds\""
    },
    {
      "resourceEmail" : "...",
      "kind" : "admin#directory#resources#calendars#CalendarResource",
      "resourceId" : "...",
      "resourceName" : "MVD11-R2-Napolitana",
      "resourceType" : "1 Tel Room",
      "etags" : "\"eqO3c9wtJJ4wVWz2xe0E9HiU_D0\/zcPwONBLID-O_3gvi0ly\""
    },
]

如何将上面的json数组转换为自定义对象数组。我正在使用SwiftyJSON来创建自定义对象。下面是我的自定义对象类。

class CalendarResource: NSObject {
     var resourceID: String
     var resourceEmail: String
     var resourceName: String
     var etags: String

    init(json: JSON) {
        self.resourceID = json[Constants.Model.CalendarResource.resourceID].stringValue
        self.resourceEmail = json[Constants.Model.CalendarResource.resourceEmail].stringValue
        self.resourceName = json[Constants.Model.CalendarResource.resourceName].stringValue
        self.etags = json[Constants.Model.CalendarResource.etags].stringValue
    }

}

由于

1 个答案:

答案 0 :(得分:1)

struct CalendarResource {
     var resourceID: String
     var resourceEmail: String
     var resourceName: String
     var etags: String 

     init(json: JSON) {
    self.resourceID = json["resourceID"].stringValue
    self.resourceEmail = json["resourceEmail"].stringValue
    self.resourceName = json["resourceName"].stringValue
    self.etags = json["etags"].stringValue
    }
}

当你得到如此反应时:

//create array somewhere outside of the method, var calendarResourceArray: [CalendarResource]

let jsonArray = response    
self.calendarResourceArray = jsonArray!.map{CalendarResource(json: $0)}