1.序列化和反序列化
- 序列化:將對象轉(zhuǎn)換為字節(jié)序列的過程,在傳遞和保存對象時,保證對象的完整性和完整性蛤铜,方便在網(wǎng)絡上傳輸或者保存在文件中
let data = try? JSONSerialization.data(withJSONObject: response)
- 反序列化:將字節(jié)序列恢復為對象的過程官研,重建對象,方便使用
let obj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
2.encode和decode
- encode:將自身類型編碼成其他外部類型
let data = try? JSONEncoder().encode(obj)
- decode:將其他外部類型解碼成自身類型
let obj = try? JSONDecoder().decode(T.self, from: data)
3.Codable
public typealias Codable = Decodable & Encodable
實際上泻骤,Codable就是指的編碼和解碼協(xié)議
4.json轉(zhuǎn)模型
4.1在用原生Codable協(xié)議的時候漆羔,需要遵守協(xié)議Codable,結(jié)構體狱掂,枚舉演痒,類都可以遵守這個協(xié)議,一般使用struct
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
}
注意趋惨,你的json里面的字段可能沒有值鸟顺,因此需要設置可選值
4.2 json數(shù)據(jù)里面的字段和model字段不一致
解決辦法:實現(xiàn) enum CodingKeys: String, CodingKey {}這個映射關系
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
var nick: String?
enum CodingKeys: String, CodingKey {
case name
case age
case sex
case name_op
case nick = "nick_name"
}
}
4.3如果你的模型里面帶有嵌套關系,比如你的模型里面有個其他模型或者模型數(shù)組,那么只要保證嵌套的模型里面依然實現(xiàn)了對應的協(xié)議
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
var nick: String?
var books_op: [BookModel]?
enum CodingKeys: String, CodingKey {
case name
case age
case sex
case name_op
case nick = "nick_name"
}
}
// BookModel
struct BookModel:Codable {
var name:String ?
}
4.4如果json里面數(shù)據(jù)類型和model數(shù)據(jù)類型不一致讯嫂,最常見的有(Bool和Int蹦锋,Int和String)這些在后臺弱類型語言上是不加區(qū)分
解決辦法:定義了一個可能是Bool或者Int的類型
struct TIntBool:Codable {
var int:Int {
didSet {
if int == 0 { self.bool = false
} else { self.bool = true }
}
}
var bool:Bool {
didSet {
if bool { self.int = 1
} else { self.int = 0 }
}
}
//自定義解碼(通過覆蓋默認方法實現(xiàn))
init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
if let intValue = try? singleValueContainer.decode(Int.self) {
self.int = intValue
self.bool = (intValue != 0)
} else if let boolValue = try? singleValueContainer.decode(Bool.self) {
self.bool = boolValue
if boolValue { self.int = 1
} else { self.int = 0 }
} else {
self.bool = false
self.int = 0
}
}
}
下面是一個Int 或者String類型的
struct TStrInt: Codable {
var int:Int {
didSet {
let stringValue = String(int)
if stringValue != string {
string = stringValue
}
}
}
var string:String {
didSet {
if let intValue = Int(string), intValue != int {
int = intValue
}
}
}
//自定義解碼(通過覆蓋默認方法實現(xiàn))
init(from decoder: Decoder) throws {
let singleValueContainer = try decoder.singleValueContainer()
if let stringValue = try? singleValueContainer.decode(String.self)
{
string = stringValue
int = Int(stringValue) ?? 0
} else if let intValue = try? singleValueContainer.decode(Int.self)
{
int = intValue
string = String(intValue);
} else
{
int = 0
string = ""
}
}
}
因此在模型設計的時候就可以這樣了:
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
var nick: String?
var books_op: [BookModel]?
var stringInt: TStrInt?
var boolInt: TIntBool?
enum CodingKeys: String, CodingKey {
case name
case age
case sex
case name_op
case nick = "nick_name"
case stringInt
case boolInt
}
}
// BookModel
struct BookModel:Codable {
var name:String ?
}
4.4使用JSONDecoder進行json轉(zhuǎn)model
private func jsonToModel<T: Codable>(_ modelType: T.Type, _ response: Any) -> T? {
guard let data = try? JSONSerialization.data(withJSONObject: response), let info = try? JSONDecoder().decode(T.self, from: data) else {
return nil
}
return info
}
先使用JSONSerialization進行一次序列化操作
看一下decode源碼:
// MARK: - Decoding Values
/// Decodes a top-level value of the given type from the given JSON representation.
///
/// - parameter type: The type of the value to decode.
/// - parameter data: The data to decode from.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.dataCorrupted` if values requested from the payload are corrupted, or if the given data is not valid JSON.
/// - throws: An error if any value throws an error during decoding.
open func decode<T : Decodable>(_ type: T.Type, from data: Data) throws -> T {//泛型并且約束遵守協(xié)議
let topLevel: Any
do {
//反序列化操作
topLevel = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: error))
}
let decoder = _JSONDecoder(referencing: topLevel, options: self.options)
//調(diào)用unbox解碼并返回解碼后的數(shù)據(jù)
guard let value = try decoder.unbox(topLevel, as: type) else {
throw DecodingError.valueNotFound(type, DecodingError.Context(codingPath: [], debugDescription: "The given data did not contain a top-level value."))
}
return value
}
可以看到在轉(zhuǎn)model的時候,先進行一次序列化操作欧芽,decode內(nèi)部又進行一次反序列化操作莉掂,蘋果這樣設計估計是在參數(shù)傳遞的時候想讓我們傳遞字節(jié)流
至此就可以使用swift原生協(xié)議Codable進行json轉(zhuǎn)model了