Codable➕SwiftyJSON数据转模型

2022-08-16  本文已影响0人  yue博客

转模型步骤

- 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
上一篇下一篇

猜你喜欢

热点阅读