Himotoki (紐解き) 是一个完全用 Swift 编写的类型安全的 JSON 解码库。该库深受流行的 Swift JSON 解析库的启发:Argo 和 ObjectMapper。
Himotoki 在日语中具有与“解码”相同的含义。
let
属性的 struct
很有用。让我们来看一个简单的例子
struct Group: Himotoki.Decodable {
let name: String
let floor: Int
let locationName: String
let optional: [String]?
// MARK: Himotoki.Decodable
static func decode(_ e: Extractor) throws -> Group {
return try Group(
name: e <| "name",
floor: e <| "floor",
locationName: e <| [ "location", "name" ], // Parse nested objects
optional: e <|? "optional" // Parse optional arrays of values
)
}
}
func testGroup() {
var JSON: [String: AnyObject] = [ "name": "Himotoki", "floor": 12 ]
let g = try? Group.decodeValue(JSON)
XCTAssert(g != nil)
XCTAssert(g?.name == "Himotoki")
XCTAssert(g?.floor == 12)
XCTAssert(g?.optional == nil)
JSON["name"] = nil
do {
try Group.decodeValue(JSON)
} catch let DecodeError.MissingKeyPath(keyPath) {
XCTAssert(keyPath == "name")
} catch {
XCTFail()
}
}
Foundation.Decodable
发生类型名称冲突,您需要将模块名称 Himotoki
添加到 Decodable
(Himotoki.Decodable
) 中。
要为您符合 Decodable
协议的模型实现 decode
方法,您可以使用以下 Extractor
的提取方法
public func value<T: Decodable>(_ keyPath: KeyPath) throws -> T
public func valueOptional<T: Decodable>(_ keyPath: KeyPath) throws -> T?
public func array<T: Decodable>(_ keyPath: KeyPath) throws -> [T]
public func arrayOptional<T: Decodable>(_ keyPath: KeyPath) throws -> [T]?
public func dictionary<T: Decodable>(_ keyPath: KeyPath) throws -> [String: T]
public func dictionaryOptional<T: Decodable>(_ keyPath: KeyPath) throws -> [String: T]?
Himotoki 还支持以下运算符来解码 JSON 元素,其中 T
是符合 Decodable
协议的泛型类型。
运算符 | 解码元素为 | 备注 |
---|---|---|
<| |
T |
一个值 |
<|? |
T? |
一个可选值 |
<|| |
[T] |
一个值数组 |
<||? |
[T]? |
一个可选的值数组 |
<|-| |
[String: T] |
一个值字典 |
<|-|? |
[String: T]? |
一个可选的值字典 |
您可以通过将值传递给 Transformer
实例,将提取的值转换为非 Decodable
类型的实例,如下所示
// Creates a `Transformer` instance.
let URLTransformer = Transformer<String, URL> { urlString throws -> URL in
if let url = URL(string: urlString) {
return url
}
throw customError("Invalid URL string: \(urlString)")
}
let url: URL = try URLTransformer.apply(e <| "foo_url")
let otherURLs: [URL] = try URLTransformer.apply(e <| "bar_urls")
Himotoki 4.x 需要/支持以下环境
目前,Himotoki 支持通过包管理器 Carthage 和 CocoaPods 进行安装。
Himotoki 与 Carthage 兼容。
github "ikesyo/Himotoki" ~> 3.1
添加到您的 Cartfile。carthage update
。Himotoki 也可以通过 CocoaPods 使用。
将以下内容添加到您的 Podfile
use_frameworks!
pod "Himotoki", "~> 3.1"
运行 pod install
。
Himotoki 在 MIT 许可证下发布。