3
我目前使用
ObjectMapper斯威夫特用於映射JSON對象從API到模型對象
Swift:如何將JSON字符串與Alamofilre或SwiftyJSON轉換爲ObjectMapper?
但我的RESTful API返回的API看起來像這樣
:
{
success: true,
data:
[{
"stats":{
"numberOfYes":0,
"numberOfNo":2,
"progress":{
"done":false,
"absolute":"2/100",
"percent":2
}
},
"quickStats":null,
"uid":5,
"name":"Flora",
"imageArray":[
"http://s3.com/impr_5329beac79400000",
"http://s3.com/impr_5329beac79400001"
],
"metaData":{
"description":"Floral Midi Dress",
"price":"40$"
}
}]
}
在數據節點陣列我不能看直到使用此代碼映射
let json = JSON(responseObject!)
for tests in json["impressions"][0] {
let test = Mapper<myTests>().map(tests)
println(test?.impressionID)
}
我該如何解決? 由於
** 編輯 ** 我發現溶液類似@tristan_him
ObjectModel映射結構
class Response: Mappable {
var success: Bool?
var data: [Data]?
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
success <- map["success"]
data <- map["data"]
}
}
class Data: Mappable {
var uid: Int?
var name: String?
// add other field which you want to map
required init?(_ map: Map) {
mapping(map)
}
func mapping(map: Map) {
uid <- map["uid"]
name <- map["name"]
}
}
映射與Alamofire響應
let response: Response = Mapper<Response>().map(responseObject)!
for item in response.data! {
let dataModel: Data = item
println(dataModel.name)
}
謝謝@triton_him – Thunderbird
@tristan_him,我們可以把「迴應'和'Data'類在兩個不同的Response.swift和Data.Swift文件中,或者我們需要將它們保存在單個.swift文件中? –
@AshishPisey,它應該以任何方式工作。這取決於你以及你想如何構建你的項目。 –