swift 字典->模型-相互轉(zhuǎn)換

***支持swift5.0***

1.swift4出現(xiàn)了Codable協(xié)議,只要繼承該協(xié)議抗楔,便可使用系統(tǒng)的模型轉(zhuǎn)換惯雳,字典轉(zhuǎn)模型已添,模型轉(zhuǎn)字典妥箕。

其實CodableDecodable協(xié)議和Encodable協(xié)議的歸結(jié)

Codable是這樣定義的:

系統(tǒng)Codable的定義

2.Decodable是用來解檔滥酥,用我的話來說更舞,就是用來Data轉(zhuǎn)換成模型。

我寫了兩種 模型轉(zhuǎn)換的方式:

2.1?一種是定義一個?LsqDecoder 類型坎吻,用于 字典缆蝉、數(shù)組轉(zhuǎn)換成模型:

struct LsqDecoder {

? ? //TODO:轉(zhuǎn)換模型(單個)

? ?public static func decode<T>(_type:T.Type, param: [String:Any]) ->T? where T: Decodable {

? ? ? ? guard let jsonData =self.getJsonData(with: param) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let model = try?JSONDecoder().decode(type, from: jsonData) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return model

? ? }

//多個

public static func decode<T>(_type:T.Type, array: [[String:Any]]) -> [T]? where T: Decodable {

? ? ? ? guard let data =self.getJsonData(with: array) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let models =try? JSONDecoder().decode([T].self, from: data) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return models

? ? }

? ? public static func getJsonData(with param:Any) ->Data? ?{

? ? ? ? if ?!JSONSerialization.isValidJSONObject(param) {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let data =try? JSONSerialization.data(withJSONObject: param, options: []) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return data

? ? }

}

附上截圖:

定義類型

2.2.一種是延展?Decodable

extension Decodable {

? ? ///dictionary->模型 temp:? Model.decode(dic)

? ? public static func decode(_dictionary: [String:Any]) ->Self? {

? ? ? ? guard let data = self.getJsonData(with: dictionary) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let model =try?JSONDecoder().decode(Self.self, from: data) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return model

? ? }

? ? ///array->模型 temp:[Model].decode(array)

? ? public static func decode(_array: [[String:Any]]) ->Self? {

? ? ? ? guard let data =self.getJsonData(with: array) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let model =try?JSONDecoder().decode(Self.self, from: data) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return model

? ? }

? ? ///JSON->模型

? ? ///此處,本人用了SwiftyJSON用于解析數(shù)據(jù)瘦真,所以添加了該方法刊头,如果沒有使用SwiftyJSON,請注釋或者刪掉以下方法

? ? /*

?? ? 如果是單個诸尽,則 Model.decode(json)

?? ? 如果是多個原杂,則 [Model].decode(json)

?? ? */

? ? public static func decode(_json:JSON) ->Self? ?{


? ? ? ? guard let data =try? json.rawData() else {

? ? ? ? ? ? retur nnil

? ? ? ? }

? ? ? ? guard let model =try?JSONDecoder().decode(Self.self, from: data) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return model

? ? }

? ? public static func getJsonData(with param:Any) -> Data? {

? ? ? ? if ?!JSONSerialization.isValidJSONObject(param) {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let data =try?JSONSerialization.data(withJSONObject: param, options: []) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return data

? ? }

}

附上截圖:

延展

3.好了,看看怎么用吧您机。

例如我有一個這樣的數(shù)據(jù)需要解析:

數(shù)據(jù)

先寫一個模型穿肄,用來接收數(shù)據(jù)

模型

使用:

單個型

如果這里,我只想解析 books际看,又咋整呢咸产?,相當(dāng)于就是數(shù)組轉(zhuǎn)多個模型啦,沒啥區(qū)別仲闽。

數(shù)組型

好了脑溢,數(shù)據(jù)轉(zhuǎn)模型說完了。

3.下面說說模型歸檔赖欣,有時候需要將模型轉(zhuǎn)換成json屑彻、字典验庙、或者數(shù)組,又該如何呢社牲?這里我也準(zhǔn)備了兩種方案壶谒。

3.1一種是定義一個?LsqEncoder 類型,用于模型轉(zhuǎn)換成字典膳沽、json字符串(集合的沒寫):

//模型轉(zhuǎn)字典汗菜,或轉(zhuǎn)json字符串

struct LsqEncoder {

? ? public static func encoder(toString model:T) ->String? where T: Encodable {

? ? ? ? let encoder =JSONEncoder()

? ? ? ? encoder.outputFormatting = .prettyPrinted

? ? ? ? guard let data =try? encoder.encode(model) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let jsonStr =String(data: data, encoding: .utf8) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return jsonStr

? ? }

? ? public static func encoder(toDictionary model:T) -> [String:Any]? where T: Encodable {

? ? ? ? let encoder =JSONEncoder()

? ? ? ? encoder.outputFormatting = .prettyPrinted

? ? ? ? guard let data =try? encoder.encode(model) else {

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? guard let dict =try?JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any] else{

? ? ? ? ? ? return nil

? ? ? ? }

? ? ? ? return dict

? ? }

}

附上圖片:

模型轉(zhuǎn)字典,或轉(zhuǎn)json字符串

3.2 第二種方案挑社,還是延展陨界。

//TODO:模型歸檔

extension Encodable {

? ? public func encoder() ->Data? {

? ? ? ? let ecd =JSONEncoder()

? ? ? ? ecd.outputFormatting = .prettyPrinted

? ? ? ? return try? ?ecd.encode(self)

? ? }

}

extension Data {

? ? ///Data->Dictionary

? ? public func toDictionary() -> [String:Any]? ?{

? ? ? ? return try? JSONSerialization.jsonObject(with: self, options: .mutableLeaves) as? ?[String:Any]

? ? }

? ? ///Data->String

? ? public func toString() ->String? {

? ? ? ? return String(data:self, encoding: .utf8)

? ? }

? ? ///Data->JSON

? ?///本人使用了SwiftyJSON,如未使用SwiftyJSON痛阻,請注釋刪除以下方法

? ? public func toJSON() ->JSON? ?{

? ? ? ? return JSON(data:self)

? ? }

? ? ///Data->Array

? ? public func toArrray() -> [Any]? {

? ? ? ? return try? JSONSerialization.jsonObject(with: self, options: .mutableLeaves) as? [Any]

? ? }

}

附上圖片:

模型歸檔

還是如何使用的問題:我們還是用剛才的數(shù)據(jù)和模型來做示例,但是模型僅僅只實現(xiàn)了Decodable協(xié)議菌瘪,所以,這里要改成


或者:

個人喜好用第二種:


好的阱当,說完了俏扩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市弊添,隨后出現(xiàn)的幾起案子录淡,更是在濱河造成了極大的恐慌,老刑警劉巖油坝,帶你破解...
    沈念sama閱讀 219,539評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嫉戚,死亡現(xiàn)場離奇詭異,居然都是意外死亡澈圈,警方通過查閱死者的電腦和手機彬檀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評論 3 396
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瞬女,“玉大人窍帝,你說我怎么就攤上這事》掏担” “怎么了坤学?”我有些...
    開封第一講書人閱讀 165,871評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長渤刃。 經(jīng)常有香客問我拥峦,道長,這世上最難降的妖魔是什么卖子? 我笑而不...
    開封第一講書人閱讀 58,963評論 1 295
  • 正文 為了忘掉前任略号,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘玄柠。我一直安慰自己突梦,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,984評論 6 393
  • 文/花漫 我一把揭開白布羽利。 她就那樣靜靜地躺著宫患,像睡著了一般。 火紅的嫁衣襯著肌膚如雪这弧。 梳的紋絲不亂的頭發(fā)上娃闲,一...
    開封第一講書人閱讀 51,763評論 1 307
  • 那天,我揣著相機與錄音匾浪,去河邊找鬼皇帮。 笑死,一個胖子當(dāng)著我的面吹牛蛋辈,可吹牛的內(nèi)容都是我干的属拾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,468評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼冷溶,長吁一口氣:“原來是場噩夢啊……” “哼渐白!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起逞频,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤纯衍,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后虏劲,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體托酸,經(jīng)...
    沈念sama閱讀 45,850評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡褒颈,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,002評論 3 338
  • 正文 我和宋清朗相戀三年柒巫,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谷丸。...
    茶點故事閱讀 40,144評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡堡掏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刨疼,到底是詐尸還是另有隱情泉唁,我是刑警寧澤,帶...
    沈念sama閱讀 35,823評論 5 346
  • 正文 年R本政府宣布揩慕,位于F島的核電站亭畜,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏迎卤。R本人自食惡果不足惜拴鸵,卻給世界環(huán)境...
    茶點故事閱讀 41,483評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧劲藐,春花似錦八堡、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至汰现,卻和暖如春挂谍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瞎饲。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評論 1 272
  • 我被黑心中介騙來泰國打工凳兵, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人企软。 一個月前我還...
    沈念sama閱讀 48,415評論 3 373
  • 正文 我出身青樓庐扫,卻偏偏與公主長得像,于是被迫代替她去往敵國和親仗哨。 傳聞我的和親對象是個殘疾皇子形庭,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,092評論 2 355

推薦閱讀更多精彩內(nèi)容