Himotoki

Join the chat at https://gitter.im/ikesyo/Himotoki

GitHub release CI Status Carthage compatible Swift Package Manager

Himotoki (紐解き) 是一个完全用 Swift 编写的类型安全的 JSON 解码库。该库深受流行的 Swift JSON 解析库的启发:ArgoObjectMapper

Himotoki 在日语中具有与“解码”相同的含义。

让我们来看一个简单的例子

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()
    }
}

⚠️ 请注意,为了避免与 Xcode 9 或更高版本中的 Foundation.Decodable 发生类型名称冲突,您需要将模块名称 Himotoki 添加到 Decodable (Himotoki.Decodable) 中。 ⚠️

为您的模型实现 decode 方法

要为您符合 Decodable 协议的模型实现 decode 方法,您可以使用以下 Extractor 的提取方法

提取运算符

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 支持通过包管理器 CarthageCocoaPods 进行安装。

Carthage

Himotoki 与 Carthage 兼容。

CocoaPods

Himotoki 也可以通过 CocoaPods 使用。

许可证

Himotoki 在 MIT 许可证下发布。