亚历山大 4.0.0

亚历山大 4.0.0

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

Caleb DavenportJonathan Baker 维护。



  • Caleb Davenport 和 Jonathan Baker

亚历山大

亚历山大是用Swift编写的一个非常简单的JSON辅助工具。它将为繁琐的JSON解包任务带来类型安全和Foundation辅助工具。

要求

Xcode Swift iOS tvOS OS X
8.0 3.0 8.0 9.0 10.9

用法

DecoderType

创建一个新的DecoderType来解包您的对象。

struct User {
    var ID: String
    var name: String
    var email: String
}

struct UserDecoder: DecoderType {
    typealias Value = User
    static func decode(JSON: Alexander.JSON) -> Value? {
        guard
            let ID = JSON["id"]?.stringValue,
            let name = JSON["name"]?.stringValue,
            let email = JSON["email"]?.stringValue
        else {
            return nil
        }
        return User(ID: ID, name: name, email: email)
    }
}

现在您可以使用let author = JSON["user"]?.decode(UserDecoder)获取单个用户,或者使用let users = JSON["users"]?.decodeArray(UserDecoder)获取用户数组。

您可以为各种类型创建DecodableType

struct SizeDecoder {
    typealias Value = CGSize
    static func decode(JSON: Alexander.JSON) -> Value? {
        guard
            let width = JSON["width"]?.doubleValue,
            let height = JSON["height"]?.doubleValue
        else {
            return nil
        }
        return CGSize(width: width, height: height)
    }
}

亚历山大包含一些用于常见类型的解码器

  • DateTimeIntervalSince1970Decoder
  • DateTimeIntervalSinceReferenceDateDecoder
  • URLDecoder
  • RawRepresentableDecoder

嵌套对象

亚历山大的大部分功能来自于其两个索引运算符:subscript[key: String] -> JSON?subscript[index: Int] -> JSON?。这些运算符允许您在不手动引用每个中间步骤的情况下解包嵌套对象。类似于let nextCursor = JSON["meta"]?["pagination"]?["next_cursor"]?.stringValue的代码仅为一行。

枚举 & RawRepresentable

您还可以解码符合RawRepresentable类型的任何内容。例如,假设以下枚举

enum Planet: String {
    case Mercury = "mercury"
    case Venus = "venus"
    case Earth = "earth"
    case Mars = "mars"
    case Jupiter = "jupiter"
    case Saturn = "saturn"
    case Uranus = "uranus"
    case Neptune = "neptune"
    // case Pluto = "pluto" =(
}

因为Planet使用String原始值类型,所以它固有地是RawRepresentable。这意味着您可以执行let planet = JSON["planet"]?.decode(RawRepresentableDecoder')let planets = JSON["planets"]?.decodeArray(RawRepresentableDecoder')