GuardedSwiftyJSON 0.7.1

GuardedSwiftyJSON 0.7.1

测试已测试
语言语言 SwiftSwift
许可证 MIT
发布上次发布2017年3月
SwiftSwift 版本3.0
SPM支持 SPM

Will James 维护。



  • Will James

GuardedSwiftyJSON

为什么我应该使用这个?

这个库使得使用 SwiftyJSON 初始化带有 JSON 数据的模型变得更加简单。

通常使用 SwiftyJSON 时,我经常会这样做

import SwiftyJSON

struct Model {
  let name : String
  let height : Double

  init?(json: JSON) {
    guard let name = json["name"].string, let height = json["height"].double else {
      return nil
    }

    self.name = name
    self.height = height
  }
}

当你有超过两三个属性需要保护你的模型时,这会变得很烦人。

示例

GuardedSwiftyJSON 通过提供一个初始化器来解决此问题,当请求的属性不存在时,初始化将失败。

import GuardedSwiftyJSON

struct Model : JsonInitializable {
  let name : String
  let height : Double

  init(json: GuardedJSON) {
    name = json["name"].string
    height = json["height"].double
  }
}

然后您将获得一个初始化器,允许它从 Swifty JSON 对象中创建

let data : JSON = ["name": "Arthur Swiftington", "height": 182.8]

let model : Model? = Model(json: data)

如果名称或高度中任何一个不存在,初始化将失败。

您可以通过使用可选前缀来指定可选属性

import GuardedSwiftyJSON

struct Model : JsonInitializable {
  let name : String
  let height : Double?

  init(json: GuardedJSON) {
    name = json["name"].string
    height = json["height"].optionalDouble
  }
}

然后,如果这些可选属性不存在,它们不会导致初始化中断。

GuardedSwiftyJSON 提供以下协议

protocol JsonInitializable {
  init?(json: JSON)
  init(json: GuardedJSON)
}

以及 init?(json: JSON) 的默认实现,它自动调用代理初始化器,如果任何所需的 JSON 属性不存在,则失败初始化。

嵌套对象

通常您会有嵌套 JSON 对象,您希望将它们表示为单独的模型。默认行为是,如果嵌套对象无效,外部的初始化将失败。例如

struct Outer : JsonInitializable {
  let inner : Inner

  init(json: GuardedJSON) {
    // since the inner json is still a GuardedJSON object in the same context,
    // if any of the properties trying to be extracted are invalid, the outer
    // initialization process will fail.
    inner = Inner(json: json["inner"])
  }
}

如果我们希望内部对象是可选的,我们应该使用内部对象的 failable 初始化器

struct Outer : JsonInitializable {
  let inner : Inner?

  init(json: GuardedJSON) {
    // here we extract the raw json object and call the failable initializer
    inner = Inner(json: json["inner"].rawJson)
  }
}

同样的方法也可以用于扁平化对象的嵌套数组,我们只想保留可以反序列化的元素

struct Outer : JsonInitializable {
  let items: [Inner]

  init(json: GuardedJSON) {
    inner = json["inner"].array.flatMap {
      return Inner(json: $0.rawJson)
    }
  }
}

具体来说,如果 inner 键不存在或不是数组,Outer 初始化将失败。否则,Outer 初始化将成功,并且数组将填充 JSON 中任何有效的元素。

因此,您可以控制初始化失败的位置。

贡献

欢迎 Pull 请求和问题。

要运行测试,您首先需要使用 Carthage 安装依赖项。

carthage update