Swift Codable 精華——手動decoder需要掌握知識點(diǎn)

注:代碼基于Swift4.0

導(dǎo)讀:Swift 4 現(xiàn)在可以支持很方便的轉(zhuǎn)模型了。例:
  1. Book結(jié)構(gòu)體 遵守Decodable協(xié)議
struct Book: Decodable {
    var title: String
    var author: String
    var rating: Float
}
  1. 自動解碼
override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let jsonString = """
{   "title": "War and Peace: A protocol oriented approach to diplomacy",
    "author": "A. Keed Decoder",
    "rating": 5.0
}
"""
        if let data = jsonString.data(using: .utf8) {
            let decoder = JSONDecoder()
            if let book = try? decoder.decode(Book.self, from: data) {
                print(book.title) //War and Peace: A protocol oriented approach to diplomacy
            } else {
                print("decode failed") 
            }
            
        }
    }
正題:老代碼可能出現(xiàn)手動Decoder怔鳖,那就探索一下吧吗铐。
一: 可選明垢,解碼用decodeIfPresent
struct Book: Decodable {
    var title: String
    var author: String
    var rating: Float?

    init(from decoder: Decoder) throws {
        let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
        title = try keyedContainer.decode(String.self, forKey: .title)
        author = try keyedContainer.decode(String.self, forKey: .author)
        rating =  try keyedContainer.decodeIfPresent(Float.self, forKey: CodingKeys.rating)
    }

    enum CodingKeys: String, CodingKey {
        case title
        case author
        case rating
    }
}
二: 非可選员辩,但json數(shù)據(jù)為nil時解碼失敗怎么辦(不想用可選撞鹉,就設(shè)置個默認(rèn)值吧)
struct Book: Decodable {
    var title: String
    var author: String
    var rating: Float

    init(from decoder: Decoder) throws {
        let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
        title = try keyedContainer.decode(String.self, forKey: .title)
        author = try keyedContainer.decode(String.self, forKey: .author)
        if let ratingValue = try keyedContainer.decodeIfPresent(Float.self, forKey: CodingKeys.rating) {
            rating = ratingValue
        } else {
            rating = 0
        }
    }

    enum CodingKeys: String, CodingKey {
        case title
        case author
        case rating
    }
}
三:decode失敗, rating為非可選痛悯,但服務(wù)給的json偏偏就不返這個字段余黎,或者返的這個字段為nil

客戶端這么寫rating

struct Book: Decodable {
    var title: String
    var author: String
    var rating: Float
    
    init(from decoder: Decoder) throws {
        let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
        title = try keyedContainer.decode(String.self, forKey: .title)
        author = try keyedContainer.decode(String.self, forKey: .author)
        rating = try keyedContainer.decode(Float.self, forKey: .rating)
    }

    enum CodingKeys: String, CodingKey {
        case title
        case author
        case rating
    }
}

服務(wù)端就想這么給數(shù)據(jù)

        let jsonString = """
{   "title": "War and Peace: A protocol oriented approach to diplomacy",
    "author": "A. Keed Decoder",
    "rating":
}
"""

或者這么返

        let jsonString = """
{   "title": "War and Peace: A protocol oriented approach to diplomacy",
    "author": "A. Keed Decoder",
}
"""

好的。 print("decode failed")
失敗倒也沒啥载萌,反正不是崩潰惧财,但是Fabric上面捕獲到N多條Non-Fatals log(就是研究這個log才有了這篇記錄)。 當(dāng)然還是要處理啦扭仁。 所以盡量用可選垮衷,或者不想給可選至少也給個默認(rèn)值吧。

四:如何通過Crashlytics捕獲異常乖坠。

在book結(jié)構(gòu)體中加一個出版日期屬性

struct Book: Decodable {
    var title: String
    var author: String
    var rating: Float
    let publishedAt: Date
    
    private static func dateDecode(_ container: KeyedDecodingContainer<CodingKeys>, key: CodingKeys) throws -> Date {
        let date: Date
        do {
            date = try container.decode(Date.self, forKey: key)
        }
        catch {
            date = Date(timeIntervalSince1970: 0)
            let dateAtString = try container.decode(String.self, forKey: key)
            let bookTitle = try container.decode(String.self, forKey: CodingKeys.title)
            
            let error = CrashlyticsError.bookDateParsingFailed(codingPath: key,
                                                               bookTitle: bookTitle,
                                                                dateValue: dateAtString)
            print(error)
//            Crashlytics.sharedInstance().recordError(error) //Fabric 可以直接記錄
        }
        
        return date
    }
    
    init(from decoder: Decoder) throws {
        let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
        title = try keyedContainer.decode(String.self, forKey: .title)
        author = try keyedContainer.decode(String.self, forKey: .author)
        rating = try keyedContainer.decode(Float.self, forKey: .rating)
        publishedAt = try Book.dateDecode(keyedContainer, key: CodingKeys.publishedAt)
    }

    enum CodingKeys: String, CodingKey {
        case title
        case author
        case rating
        case publishedAt
    }
    
//string 轉(zhuǎn)date會用到
    static func dateFormatter() -> DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        return dateFormatter
    }
}

加一個捕獲異常CrashlyticsError文件

import UIKit

enum CrashlyticsError: CustomNSError {
    case bookParsingFailed(codingPath: [CodingKey], debugDescription: String)
    case bookDateParsingFailed(codingPath: CodingKey, bookTitle: String, dateValue: String)
    
    static var errorDomain: String {
        return "XXDecoderDemo"
    }
    
    var errorCode: Int {
        switch self {
        case .bookParsingFailed(_, _):
            return 7780
        case .bookDateParsingFailed(_,_,_):
            return 7781
        }
    }
    
    var errorUserInfo: [String : Any] {
        switch self {
        case .bookParsingFailed(let codingPath, let debugDescription):
            var userInfo = [NSLocalizedDescriptionKey :  "Book Parsing",
                            NSLocalizedFailureReasonErrorKey : "Can't parse",
                            "Description" : debugDescription]
            for (index, element) in codingPath.enumerated() {
                userInfo["Coding Key \(index)"] = element.stringValue
            }
            return userInfo
            
        case .bookDateParsingFailed(let codingPath, let bookTitle, let dateValue):
            return [NSLocalizedDescriptionKey :  "Book Date Parsing",
                    NSLocalizedFailureReasonErrorKey : "Can't parse \(codingPath.stringValue)",
                "Book Title"   : bookTitle,
                "Date value" : dateValue]
        }
    }
}

viewDidLoad代碼搀突。這里publishedAt的jsonString故意寫成錯的格式,然后進(jìn)入到捕獲異常程序熊泵。正常格式應(yīng)是:2018-01-01T00:00:00.000Z(和dateFormatter保持一致)

override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let jsonString = """
{   "title": "War and Peace: A protocol oriented approach to diplomacy",
    "author": "A. Keed Decoder",
    "rating": 5.0,
    "publishedAt": "019-04-16T9:24:37TPM.000Z"

}
"""
        if let data = jsonString.data(using: .utf8) {
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .formatted(Book.dateFormatter())
            if let book = try? decoder.decode(Book.self, from: data) {
                print(book.title) //War and Peace: A protocol oriented approach to diplomacy
            } else {
                print("decode failed")
            }
            
        }
    }

可想而知仰迁,最終解碼不會失敗,還是會打印出書名顽分。

總結(jié):雖然獲取到的publishedAt是錯的格式轩勘,轉(zhuǎn)化成date會不成功,但是進(jìn)行了異常捕獲怯邪,在catch代碼塊中,將date設(shè)置成date = Date(timeIntervalSince1970: 0)花墩,也相當(dāng)于是設(shè)置默認(rèn)值了悬秉。解碼不失敗澄步, 同時還記錄了為什么沒有轉(zhuǎn)化成功的log。 可以快速定位到出問題的那條信息和泌。 完美村缸!

捕獲到的error信息如下(Fabric記錄的話,會更加清晰):

print(error)  //bookDateParsingFailed(codingPath: CodingKeys(stringValue: "publishedAt", intValue: nil), bookTitle: "War and Peace: A protocol oriented approach to diplomacy", dateValue: "019-04-16T9:24:37TPM.000Z")

空了會將demo上傳武氓。

每天學(xué)習(xí)一點(diǎn)點(diǎn)梯皿,加油??!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末县恕,一起剝皮案震驚了整個濱河市东羹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌忠烛,老刑警劉巖属提,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異美尸,居然都是意外死亡冤议,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門师坎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恕酸,“玉大人,你說我怎么就攤上這事胯陋∪镂拢” “怎么了?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵惶岭,是天一觀的道長寿弱。 經(jīng)常有香客問我,道長按灶,這世上最難降的妖魔是什么症革? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮鸯旁,結(jié)果婚禮上噪矛,老公的妹妹穿的比我還像新娘。我一直安慰自己铺罢,他們只是感情好艇挨,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著韭赘,像睡著了一般缩滨。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天脉漏,我揣著相機(jī)與錄音苞冯,去河邊找鬼。 笑死侧巨,一個胖子當(dāng)著我的面吹牛舅锄,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播司忱,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼皇忿,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了坦仍?” 一聲冷哼從身側(cè)響起鳍烁,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎桨踪,沒想到半個月后老翘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡锻离,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年铺峭,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片汽纠。...
    茶點(diǎn)故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡卫键,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出虱朵,到底是詐尸還是另有隱情莉炉,我是刑警寧澤,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布碴犬,位于F島的核電站絮宁,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏服协。R本人自食惡果不足惜绍昂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望偿荷。 院中可真熱鬧窘游,春花似錦、人聲如沸跳纳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽寺庄。三九已至艾蓝,卻和暖如春力崇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背饶深。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工餐曹, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人敌厘。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像朽合,于是被迫代替她去往敵國和親俱两。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評論 2 355