Codable?SwiftyJSON數據轉模型

轉模型步驟

- 1.獲取到數據后使用JSON進行包裝
- 2.通過JSON獲取rawData
- 3.使用`JSONDecoder().decode<T>(_ type: T.Type, from data: Data)`轉為模型

decode函數

public extension JSON {
    func decodeObjcet<T>(_ type: T.Type) -> T? where T: Decodable {
        do {
            let data = try self.rawData()
            let result = try JSONDecoder().decode(type, from: data)
            return result
        } catch SwiftyJSONError.invalidJSON {
            if type == JSON.self {
                return self as? T
            }
            return self.rawValue as? T
        } catch {
            return nil
        }
    }
}

聲明數據模型

struct、class、enum可按需使用,并遵守Codable協議。
舉例說明:
一個描述一個人姓名、性別、教育經歷等信息的json數據如下

{
    "age": 20,
    "name": "大碗",
    "sex": 1,
    "haveJob": false,
    "educations": [
          {
              "rank" : 1,
              "schoolName" : "春我部小學"
          },
          {
              "rank" : 2,
              "schoolName" : "春我部初級中學"
          },
          {
              "rank" : 3,
              "schoolName" : "春我部高級中學"
          }
    ]
}

可聲明數據模型如下

enum Sex: Int, Codable {
    case man = 1
    case woman = 2
}
enum EducationRank: Int, Codable {
    case primary = 1
    case juniorMiddle = 2
    case seniorMiddle = 3
    case university = 4
    case masterDegreeCandidate = 5
    case doctoralCandidate = 6
}
struct Education: Codable {
    var rank: EducationRank?
    var schoolName: String?
}
struct Person: Codable {
    /// 年齡
    var age: Int?
    /// 姓名
    var name: String?
    /// 性別
    var sex: Sex?
    /// 是否有工作
    var haveJob: Bool?
    /// 受教育經歷
    var educations: [Education]?
}

調用var dawan = JSON(json).decodeObjcet(Person.self)即可完成最基礎的數據轉模型了。

數據類型Bool

上面的例子,網絡數據里,表示Bool類型可能不會用true false,而是用10表示,那么使用Bool類型聲明的haveJob屬性則無法正常解析,對于這種情況可以使用一個結構體包裹數據,并實現init(from decoder: Decoder)函數,然后提供獲取bool值的方法或屬性。SwiftyJSON的 JSON類型正好可以滿足這個需求,聲明var haveJob: JSON?,使用時,調用JSONboolboolValue進行判斷。

默認值

網絡數據里,所有的字段都可能是缺失的,故聲明的屬性都是可選擇類型。
但這樣做在寫代碼會產生大量的可選值判斷

if (dawan.age ?? 0) > 18 {
    // 成年
}
if let name = dawan.name, !name.isEmpty {
    // 名字
}
if dawan.haveJob ?? false {
    // 有工作
}

以上這些代碼,其實是相當于給到這些屬性一個默認值的,即0、 ""、 false。
為了給這些屬性設定默認值,要使用到@propertyWrapper屬性包裝器:

/// 默認值協議
public protocol DefaultValue {
    associatedtype Value: Codable
    static var defaultValue: Value { get }
}

@propertyWrapper
/// 默認值包裝器
public struct Default<T: DefaultValue> {
    public var wrappedValue: T.Value
    public init(wrappedValue: T.Value) {
        self.wrappedValue = wrappedValue
    }
}
extension Default: Codable {
    /**
     ## 對Codable協議進行處理
     ### decode時當沒有對應值時,賦值為默認值
     ### encode時保證正確的結構層級,避免 @propertyWrapper 對結構層級造成`"key":{"wrappedValue"=value}`這樣的影響
     */
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        wrappedValue = (try? container.decode(T.Value.self)) ?? T.defaultValue
    }
    public func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(self.wrappedValue)
    }
}
public extension KeyedDecodingContainer {
    /// 當json中不含有對應key時,為其賦值為默認值
    func decode<T>(_ type: Default<T>.Type, forKey key: Key) throws -> Default<T> where T: DefaultValue {
        (try decodeIfPresent(type, forKey: key)) ?? Default(wrappedValue: T.defaultValue)
    }
}

然后給常用的幾種數據類型遵守DefaultValue協議

extension Bool: DefaultValue {
    public static var defaultValue: Bool = false
}
extension Int: DefaultValue {
    public static var defaultValue: Int = 0
}
extension Double: DefaultValue {
    public static var defaultValue: Double = 0
}
extension String: DefaultValue {
    public static var defaultValue: String = ""
}

枚舉類型默認值

public protocol EnumCodable: RawRepresentable, Codable where RawValue: Codable {
    static var defaultCase: Self { get }
}
extension EnumCodable {
    public init(from decoder: Decoder) throws {
        if let container = try? decoder.singleValueContainer(), !container.decodeNil() {
            let decoded = try container.decode(RawValue.self)
            self = Self.init(rawValue: decoded) ?? .defaultCase
        } else {
            self = .defaultCase
        }
    }
}

對上面的Sex枚舉可以做如下改動

enum Sex: Int, Codable {
    case unknow = 0
    case man = 1
    case woman = 2
}
extension Sex: EnumCodable {
    static var defaultCase: Sex = .unknow
}
extension Sex: DefaultValue {
    static var defaultValue: Sex = .defaultCase
}

也可以免去EnumCodable這一步

enum Sex: Int, Codable {
    case unknow = 0
    case man = 1
    case woman = 2
}
extension Sex: DefaultValue {
    static var defaultValue: Sex = . unknow
}

設定默認值后的Person模型如下:

struct Person: Codable {
    /// 年齡
    @Default<Int>var age: Int
    /// 姓名
    @Default<String>var name: String
    /// 性別
    @Default<Sex>var sex: Sex
    /// 是否有工作
    var haveJob: JSON?
    /// 受教育經歷
    var educations: [Education]?
}

數組默認值

如果要對數組設定默認值,可以使用typealias后遵守DefaultValue協議

typealias Educations = [Education]
extension Educations: DefaultValue {
    static var defaultValue: [Education] = [Education]()
}

@Default<Educations>var educations: Educations
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容