美文网首页
Swift学习笔记(四)HandyJSON序列化

Swift学习笔记(四)HandyJSON序列化

作者: Geniune | 来源:发表于2018-05-15 15:32 被阅读14次

    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

    相关文章

      网友评论

          本文标题:Swift学习笔记(四)HandyJSON序列化

          本文链接:https://www.haomeiwen.com/subject/xozedftx.html