swift学习专题

HandyJSON与SwiftyJSON的使用

2020-07-19  本文已影响0人  菲特峰

HandJSON的使用参考

https://www.jianshu.com/p/e9d933ce7c74

class BaseModel: HandyJSON,Codable {
    required init() {}
     func mapping(mapper: HelpingMapper) {   //自定义解析规则,日期数字颜色,如果要指定解析格式,子类实现重写此方法即可
    //        mapper <<<
    //            date <-- CustomDateFormatTransform(formatString: "yyyy-MM-dd")
    //
    //        mapper <<<
    //            decimal <-- NSDecimalNumberTransform()
    //
    //        mapper <<<
    //            url <-- URLTransform(shouldEncodeURLString: false)
    //
    //        mapper <<<
    //            data <-- DataTransform()
    //
    //        mapper <<<
    //            color <-- HexColorTransform()
          }
}

具体json转model需要

以下是我项目中使用的代码
后台返回json

{
"code": 200,
"data": {
"result": [
{
"id": 39,
"img": "http://pxs3-img-test.oss-cn-shenzhen.aliyuncs.com/uploads/image/20200429092338/8ad5a28a461104d941bca939a0919d05d231d9c1.png?city_id=441900&platform_id=2",
"img_width": "",
"img_height": "",
"bg_images": "https://pxs3-img.oss-cn-shenzhen.aliyuncs.com/defauit_overall_img.png?city_id=441900&platform_id=2",
"bg_images_width": "",
"bg_images_height": "",
"jump_type": 1,
"jump_view": "shop_success",
"jump_param": ""
}
]
},
"msg": "SUCCESS"
}

配合SwiftyJSON框架转模型

JSON转数组模型

    func loadBannerData(position:String) {
        
        HttpRequest.loadData(target: PXSHomeAPI.banner(position: position), success: { (data) in
            let json = JSON(data)
            if let imageArr = JSONDeserializer<ImageModel>.deserializeModelArrayFrom(json: json["data"]["result"].description) {
            self.updateDataBlock?()

        }) { (code, msg) in
            
        }
        
    }

JSON转模型

后台JSON数据:
> {
    "code": 200,
    "data": {
        "result": {
            "transfer_shop": "2124",   //在线转店
            "transfer_success": 1788,  //转店成功
            "find_shop": 0            //找店成功
        }
    },
    "msg": "SUCCESS"
}



    func loadCountData() {
        HttpRequest.loadData(target: PXSHomeAPI.statistics, success: { (res) in
            let json = JSON(res)
            
            if let model = JSONDeserializer<PXSHomeCountModel>.deserializeFrom(json: json.description, designatedPath: "data.result") {
                self.countModel = model
                self.updateDataBlock?()
            }

        }) { (code, message) in
            
        }
    }

上一篇下一篇

猜你喜欢

热点阅读