在封装数据时是否有必要为AlamofireObjectMapper编写包装器对象?例如。如果天气数据将在命名数组“数据”内。什么是映射的最佳解决方案?
{
"data": [
{
"conditions": "Partly cloudy",
"day": "Monday",
"temperature": 20
},
{
"conditions": "Showers",
"day": "Tuesday",
"temperature": 22
},
{
"conditions": "Sunny",
"day": "Wednesday",
"temperature": 28
}
]
}
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
Alamofire.request(.GET, URL, parameters: nil)
.responseArray { (response: [Forecast]?, error: ErrorType?) in
if let response = response {
for forecast in response {
print(forecast.day)
print(forecast.temperature)
}
}
}
答案 0 :(得分:1)
事实上,这是最舒适的选择。
你可以有一个包装对象,如:
class Forecast: Mappable {
// MARK: - Attributes
var conditions: String = ""
var day: String = ""
var temperature: NSNumber
// MARK: - Methods
init() { }
required init?(_ map: Map) { }
func mapping(map: Map) {
conditions <- map["conditions"]
day <- map["day"]
temperature <- map["temperature"]
}
}
然后,管理请求:
Alamofire.request(.POST, URL).responseObject({ (response: Response<Forecast, NSError>) -> Void in
if response.result.isSuccess {
print(response.result.value!)
}
})
祝你好运!
答案 1 :(得分:0)
所以查看文档,看起来数据是在请求级别指定的,如下面的示例所示:
{{1}}关键是:
Alamofire.request(.GET,URL).responseObject(&#34; data&#34;){(回复:
答案 2 :(得分:0)
您可以使用AnyObject映射响应,例如下面的示例;
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
Alamofire.request(.GET, URL).responseJSON { (response : Response<AnyObject, NSError>) -> Void in
print(response.result.value.debugDescription)
let arr = response.result.value! as? Array<AnyObject>
for a in arr! {
let condition = a["conditions"]
let day = a["day"]
print("\(day!!) condition is \(condition!!)")
}
}
输出:
Monday condition is Partly cloudy
Tuesday condition is Showers
Wednesday condition is Sunny