前言
在swift4.0后,蘋果官方在Foundation框架中添加了Codable協(xié)議可用于JSON解析為Model和Model轉(zhuǎn)化為JSON。除了一些三方JSON解析庫(kù)外,我們又有了新的選擇,使用起來(lái)也較為方便。
應(yīng)用
- 首先定義需要的數(shù)據(jù)結(jié)構(gòu),必須遵循Codable協(xié)議,因?yàn)榻馕鲞^(guò)程中是可能出現(xiàn)沒(méi)有對(duì)應(yīng)屬性的情況的,所以屬性需要設(shè)置為可選型。另外支持支持自定義鍵值對(duì),需要定義CodingKeys,并且對(duì)所有的屬性進(jìn)行定義,否則會(huì)報(bào)錯(cuò)
struct Student: Codable {
var name: String?
var num: Int?
var height: Float?
var pens: [Pen]?
//自定義鍵值對(duì), 一旦聲明所以的屬性都需要定義
enum CodingKeys: String, CodingKey {
case name = "name"
case num = "number"
case height
case pens
}
}
struct Pen: Codable {
var type: String?
var price: Float?
}
- 接下來(lái)對(duì)解析方法進(jìn)行簡(jiǎn)單的封裝,這樣就不用每次都重復(fù)寫解析方法了
//json->model
func jsonToModel<T>(_ json: Any, modelType: T.Type) -> T? where T: Codable {
var jsonDic: Any = json
//如果傳入的是json字符串,需要進(jìn)行轉(zhuǎn)換
if type(of: json) == String.self {
let jsonStr = json as! String
guard let jsonData = jsonStr.data(using: String.Encoding.utf8, allowLossyConversion: false) else {
return nil
}
guard let jsonObjct = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {
return nil
}
jsonDic = jsonObjct
}
if !JSONSerialization.isValidJSONObject(jsonDic) {
print("json format error")
return nil;
}
let jsonDecoder = JSONDecoder()
guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonDic, options: []) else { return nil}
guard let model = try? jsonDecoder.decode(modelType, from: jsonData) else {return nil}
return model
}
//model->json
func modelToJson<T>(model: T) -> Any? where T: Codable {
let jsonEncoder = JSONEncoder()
guard let jsonData = try? jsonEncoder.encode(model) else { return nil}
guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {return nil}
return json
}
- 接下來(lái)進(jìn)行簡(jiǎn)單測(cè)試
//json->model
print("-----------json->model------------------")
let dic:[String:Any] = ["name":"Jack",
"number":123,
"height": 175.5,
"pens": [["type": "gangbi", "price": 25.0],
["type": "shuibi", "price": 2.0]]
]
let student1 = jsonToModel(dic, modelType: Student.self)
print(student1 ?? "parse fail")
//model->json
print("-----------model->json------------------")
let student2: Student = Student(name: "Rose", num: 3, height: 168.5, pens: [Pen(type: "qianbi", price: 1.5)])
let ret = modelToJson(model: student2)
print(ret ?? "parse fail")
//json string -> model
print("-----------json string -> model------------------")
let jsonStr = "{\"type\":\"maobi\",\"price\":100.0}"
let myPen = jsonToModel(jsonStr, modelType: Pen.self)
print(myPen ?? "parse fail")
打印結(jié)果如下:
-----------json->model------------------
Student(name: Optional("Jack"), num: Optional(123), height: Optional(175.5), pens: Optional([SwiftPhone.Pen(type: Optional("gangbi"), price: Optional(25.0)), SwiftPhone.Pen(type: Optional("shuibi"), price: Optional(2.0))]))
-----------model->json------------------
{
height = "168.5";
name = Rose;
number = 3;
pens = (
{
price = "1.5";
type = qianbi;
}
);
}
-----------json string -> model------------------
Pen(type: Optional("maobi"), price: Optional(100.0))
可以看到JSON和Model間的成功轉(zhuǎn)換,并且Student結(jié)構(gòu)體的num屬性映射到了number。
思考
-
通過(guò)原生Codable協(xié)議進(jìn)行JSON和Model的轉(zhuǎn)換優(yōu)勢(shì)在哪呢?
不再依賴于第三方庫(kù),接口相對(duì)更穩(wěn)定,不會(huì)因?yàn)榘姹镜纳?jí)而導(dǎo)致無(wú)法使用的情況。 -
Codable協(xié)議是否會(huì)同時(shí)對(duì)父類進(jìn)行解析?
因?yàn)閟wift的struct是無(wú)法繼承的,所以不存在解析父結(jié)構(gòu)的情況。同時(shí),經(jīng)過(guò)驗(yàn)證,Codable協(xié)議對(duì)class是無(wú)效的。所以不存在這一的場(chǎng)景。