Swift学习笔记(四)HandyJSON序列化
2018-05-15 本文已影响14人
Geniune
GitHub:https://github.com/alibaba/HandyJSON
根据返回数据格式进行建Model:
struct WeatherModel: HandyJSON {
var shidu : String?
var wendu : String?
var pm25 : String?
var pm10 : String?
var quality : String?
var yesterday : WeatherListModel?//昨日天气
var forecast : Array<WeatherListModel>?//未来几天天气
}
struct WeatherListModel: HandyJSON {
var api : String?
var type : String?
var date : String?//日期
var sunrise : String?//日出
var sunset : String?//日落
var high : String?//最高温
var low : String?//最低温
var fx : String?//东南风
var fl : String?//4-5级
}
发起Http请求在成功后block序列化的Model对象
static func weather(city:String, success:((_ model:WeatherModel?) -> Void)?, failure:((_ e:HttpException) -> Void)?) -> Void {
let requestURL = "https://www.sojson.com/open/api/weather/json.shtml"//接口URL
var modelR = CityWeatherModelR.init()//入参Model对象
modelR.city = city//赋值
let paramer : Dictionary = modelR.toJSON()!//反序列化成Dictionary
HttpClient.GET(url: requestURL, params: paramer, success: { (responseObj) in
if let object = WeatherModel.deserialize(from: responseObj) {//序列化成Model
success!(object)
}
}) { (e) in
failure!(e)
}
}
在视图控制器中,获取上海市的天气信息:
NetworkAPI.weather(city: "上海", success: { (model) in
self.dataArr = model?.forecast;//未来几日天气预报数组
self.tableView.reloadData()
}) { (e) in
print("获取失败,原因:\(e.message!)");
}
最后附上我写的Demo:https://github.com/Geniune/LearnSwift