Swift筆記34:ObjectMapper

ObjectMapper的基本使用

1 引入import ObjectMapper
2 創(chuàng)建基本數(shù)據(jù)模型
(2.1) 建立數(shù)據(jù)模型,遵守 Mappable
(2.2 ) 實現(xiàn)Mappable協(xié)議的方法。required init?(map: ObjectMapper.Map) {}
func mapping(map: ObjectMapper.Map) {}
3 ObjectMapper接收數(shù)據(jù),然后就會自動映射到屬性,我們可以點語法直接使用

查看demo

需要解析的數(shù)據(jù)
{
    "list": [
        {
            "id": 1000,
            "avatar": "4e7f0c83ly8g1ho507078j20ro0rojtq.jpg",
            "vip": true,
            "name": "婁藝瀟",
            "date": "2020-01-05 22:51",
            "isFollowed": false,
            "text": "潮汕菜太好吃了,暴飲暴食后的我為了明天能穿上演出禮服,不得不徒步走回酒店,邊走邊鍛煉,別夸我敬業(yè),畢竟彩排完我還想吃頓宵夜。[允悲]還有啥推薦的美食不?",
            "images": [
                "4e7f0c83gy1gam2misv31j21hc0u016k.jpg",
                "4e7f0c83gy1gam2mjhk8zj21hc0v6wnx.jpg",
                "4e7f0c83gy1gam2ml6nucj22tc240kjl.jpg",
                "4e7f0c83gy1gam2mn58d3j22tc240qv5.jpg",
                "4e7f0c83gy1gam2mp0x4pj22tc240u0x.jpg",
                "4e7f0c83gy1gam2mr1b81j22tc2407wi.jpg"
            ],
            "commentCount": 2200,
            "likeCount": 11319,
            "isLiked": true
        }
}
創(chuàng)建數(shù)據(jù)模型
import Foundation
import ObjectMapper

/// 關(guān)注名單
struct FocusList: Mappable {
    var list: [UserInfo]?
    mutating func mapping(map: ObjectMapper.Map) {
        list <- map["list"]
    }

    init?(map: ObjectMapper.Map) {}
}

/// 用戶信息
class UserInfo: Mappable {
    var id: Int?
    var avatar: String?
    var vip: Bool?
    var name: String?
    var date: Date?
    var isFollowed: Bool?
    var text: String?
    var test: String?
    var images: [Any]?
    var commentCount: Int?
    var likeCount: Int?
    var isLiked: Bool?

    required init?(map: ObjectMapper.Map) {}
    // 如果漏寫了map,解析的不到數(shù)據(jù),默認為nil
    func mapping(map: ObjectMapper.Map) {
        id <- map["id"]
        avatar <- map["avatar"]
        vip <- map["vip"]
        name <- map["name"]
        isFollowed <- map["isFollowed"]
        text <- map["text"]
        test <- map["test"]
        images <- map["images"]
        commentCount <- map["commentCount"]
        likeCount <- map["likeCount"]
        isLiked <- map["isLiked"]
        date <- (map["date"], DateTransform())
    }
}

struct UserSubDetail: Mappable {
    var desc: String?
    var name: String?
    var num: Int?

    mutating func mapping(map: ObjectMapper.Map) {
        desc <- map["desc"]
        name <- map["name"]
        num <- map["num"]
    }

    init?(map: ObjectMapper.Map) {}
}

具體使用

在不使用嵌套模型,只利用class UserInfo的情況下解析服務(wù)器返回的數(shù)據(jù)并應(yīng)用。

func loadNewData() {
    let url = GlobalConfig.USERDETAIL_URL
    let parameters = ["key": "value"]
    DispatchQueue.global().async {
        Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: { [weak self] response in
            guard let res = response.result.value, let weakSelf = self else { return }
            let dic = res as? [String: Any]
            let arr = dic?["list"] as? [[String: Any]]
            guard let arrT = arr else { return }
            weakSelf.userItems.removeAll()
            weakSelf.userItems = Mapper<UserInfo>().mapArray(JSONArray: arrT)
            weakSelf.mTableView.reloadData()
        })
    }
}
print("----1---->", userInfo.id as Any) // Optional(1000)
print("----2---->", userInfo.avatar as Any) // Optional("4e7f0c83ly8g1ho507078j20ro0rojtq.jpg")
print("----3---->", userInfo.vip as Any) // Optional(true)
print("----4---->", userInfo.name as Any) // Optional("婁藝瀟")
print("----5---->", userInfo.date as Any) // Optional(1970-01-01 00:33:40 +0000)
print("----6---->", userInfo.text as Any) // Optional("潮汕菜太好吃了")
print("----7---->", userInfo.images as Any) // Optional([4e7f0c83gy1gam2misv31j21hc0u016k.jpg, 4e7f0c83gy1gam2mjhk8zj21hc0v6wnx.jpg, 4e7f0c83gy1gam2ml6nucj22tc240kjl.jpg, 4e7f0c83gy1gam2mn58d3j22tc240qv5.jpg, 4e7f0c83gy1gam2mp0x4pj22tc240u0x.jpg, 4e7f0c83gy1gam2mr1b81j22tc2407wi.jpg])

使用嵌套模型,利用struct FocusList 和 class UserInfo的情況下解析服務(wù)器返回的數(shù)據(jù)并應(yīng)用。

func loadNewData() {
    let url = GlobalConfig.USERDETAIL_URL
    let parameters = ["key": "value"]
    DispatchQueue.global().async {
        Alamofire.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON(completionHandler: { [weak self] response in
            guard let res = response.result.value, let weakSelf = self else { return }
            let focusList = Mapper<FocusList>().map(JSONObject: res)
            guard let userItemsTemp = focusList?.list else { return }
            // 逃逸閉包用到self,以及它的屬性需要捕獲一下.[weak self]表示弱引用,弱引用肯定是可選類型
            weakSelf.userItems.removeAll()
            weakSelf.userItems = userItemsTemp
            weakSelf.mTableView.reloadData()
        })
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容