首先建立本身的模型類,而後倒入頭文件數組
import ObjectMapper 實現 ObjectMapper 的協議 Mappable:app
class Statuses: Mappable {ui
} 在模型類的下面實現協議方法:code
required init?(_ map: Map) {ip
}it
func mapping(map: Map) {io
} JSON數據:class
{ "statuses": [ { "created_at": " ", "id": 1, "text": " ", "source": " ", "user": { "id": , "name": " ", "description": " ", } }, ... ], ... } 建立數據模型 class Model: Mappable {import
var created_at: String? var id: Int = 0 var text: String? var source: String? var user: ?? required init?(_ map: Map) { } func mapping(map: Map) { }
} 當還存在另外一個數據模型時,一樣再次建立一個模型 class Model2: Mappable {require
var id: Int = 0 var name: String? var description: String? required init?(_ map: Map) { } func mapping(map: Map) { }
} 模型賦值 在 Model 類中找到 func mapping(map: Map) 這個方法 func mapping(map: Map) {
created_at <- map["created_at"] id <- map["id"] text <- map["text"] source <- map["source"] user <- map["user"] }
在 Model2 類中找到 func mapping(map: Map) 這個方法 func mapping(map: Map) { id <- map["id"] name <- map["name"] description <- map["description"] }
經過 <- 符號取值 public func <- <T>(inout left: T?, right: Map) { switch right.mappingType { case .FromJSON where right.isKeyPresent: FromJSON.optionalBasicType(&left, object: right.value()) case .ToJSON: ToJSON.optionalBasicType(left, map: right) default: () } } 轉成模型 let modelArr = Mapper<Model>().mapArray(/把你的模型數據放進來/) modelArr 的類型是這樣的 [Model]? 一個存放了 Model 類型的數組
轉成 JSON let statusJson = status.toJSON()