1.序列化和反序列化
- 序列化:將對(duì)象轉(zhuǎn)換為字節(jié)序列的過(guò)程,在傳遞和保存對(duì)象時(shí),保證對(duì)象的完整性和完整性,方便在網(wǎng)絡(luò)上傳輸或者保存在文件中
let responseData = try? JSONSerialization.data(withJSONObject: response)
- 反序列化:將字節(jié)序列恢復(fù)為對(duì)象的過(guò)程,重建對(duì)象,方便使用
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
實(shí)際上,Codable就是指的編碼和解碼協(xié)議
4.json轉(zhuǎn)模型
4.1在用原生Codable協(xié)議的時(shí)候,需要遵守協(xié)議Codable,結(jié)構(gòu)體,枚舉,類都可以遵守這個(gè)協(xié)議,一般使用struct
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
}
注意,你的json里面的字段可能沒有值,因此需要設(shè)置可選值
4.2 json數(shù)據(jù)里面的字段和model字段不一致
解決辦法:實(shí)現(xiàn) enum CodingKeys: String, CodingKey {}這個(gè)映射關(guān)系
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"
}
}
上訴代碼中,如果后臺(tái)返回的字段名稱叫做nick_name,但是你想用自己命名的nick,就可以用到上述枚舉中的映射去替換你想要的字段名字。
4.3如果你的模型里面帶有嵌套關(guān)系,比如你的模型里面有個(gè)其他模型或者模型數(shù)組,那么只要保證嵌套的模型里面依然實(shí)現(xiàn)了對(duì)應(yīng)的協(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)這些在后臺(tái)弱類型語(yǔ)言上是不加區(qū)分
解決辦法:定義了一個(gè)可能是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 }
}
}
//自定義解碼(通過(guò)覆蓋默認(rèn)方法實(shí)現(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
}
}
}
下面是一個(gè)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
}
}
}
//自定義解碼(通過(guò)覆蓋默認(rèn)方法實(shí)現(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 = ""
}
}
}
因此在模型設(shè)計(jì)的時(shí)候就可以這樣了:
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進(jìn)行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進(jìn)行一次序列化操作
看一下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的時(shí)候,先進(jìn)行一次序列化操作,decode內(nèi)部又進(jìn)行一次反序列化操作,蘋果這樣設(shè)計(jì)估計(jì)是在參數(shù)傳遞的時(shí)候想讓我們傳遞字節(jié)流
至此就可以使用swift原生協(xié)議Codable進(jìn)行json轉(zhuǎn)model了
JSON字符串轉(zhuǎn)模型
這是一個(gè)字符串
let jsonString:String = """
{
"name":"Tomas",
"age":"10",
"gender":"man"
}
"""
如果將它解析成User對(duì)象
let jsonData: Data = jsonString.data(using:String.Encoding.utf8)!
let decoder = JSONDecoder()
do {
let user:UserModel = try decoder.decode(UserModel.self,from:jsonData)
} catch {
}
JSONSerialization
Serialization 是序列化的意思,JSONSerialization 顧名思義是對(duì)JSON進(jìn)行序列化。
JSONSerialization 是對(duì) JSON 字符串進(jìn)行序列化和反序列化的工具類。用這個(gè)類可以將JSON轉(zhuǎn)成對(duì)象,也可以將對(duì)象轉(zhuǎn)成JSON。
let dict:[String:Any] = ["name":"jack",
"age":10,
"gender":"man"]
if JSONSerialization.isValidJSONObject(dict) == false {
return
}
let data:Data = try! JSONSerialization.data(withJSONObject: dict, options: .fragmentsAllowed);
// 將data轉(zhuǎn)換成制定model
guard let Model:UserModel = try? JSONDecoder().decode(UserModel.self, from: data) else {
return
}
// 將data轉(zhuǎn)成字符串輸出
let string = String(data: data, encoding: String.Encoding.utf8)
print(string)
print(Model.name)
Optional("{\"name\":\"jack\",\"gender\":\"man\",\"age\":10}")
Optional("jack")
- JSON轉(zhuǎn)字典
let jsonString = "{\"name\":\"jack\",\"age\":10}";
let data = jsonString.data(using: .utf8)
let dict = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(dict)