1.序列化和反序列化
- 序列化:将对象转换为字节序列的过程,在传递和保存对象时,保证对象的完整性和完整性,方便在网络上传输或者保存在文件中
let data = try? JSONSerialization.data(withJSONObject: response)
- 反序列化:将字节序列恢复为对象的过程,重建对象,方便使用
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就是指的编码和解码协议
4.json转模型
4.1在用原生Codable协议的时候,需要遵守协议Codable,结构体,枚举,类都可以遵守这个协议,一般使用struct
struct UserModel:Codable {
var name: String?
var age: Int?
var sex: Bool?
var name_op: String?
}
注意,你的json里面的字段可能没有值,因此需要设置可选值
4.2 json数据里面的字段和model字段不一致
解决办法:实现 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如果你的模型里面带有嵌套关系,比如你的模型里面有个其他模型或者模型数组,那么只要保证嵌套的模型里面依然实现了对应的协议
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里面数据类型和model数据类型不一致,最常见的有(Bool和Int,Int和String)这些在后台弱类型语言上是不加区分
解决办法:定义了一个可能是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 }
}
}
//自定义解码(通过覆盖默认方法实现)
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
}
}
}
//自定义解码(通过覆盖默认方法实现)
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转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 {//泛型并且约束遵守协议
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)
//调用unbox解码并返回解码后的数据
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
}
可以看到在转model的时候,先进行一次序列化操作,decode内部又进行一次反序列化操作,苹果这样设计估计是在参数传递的时候想让我们传递字节流
至此就可以使用swift原生协议Codable进行json转model了