Stork
Stork 是一个轻量级库,旨在使 JSON 到类型之间的转换尽可能平滑。Stork 崇尚简洁、明确和控制。
基于函数式编程原则,并温和地受到 Aeson 的启发,Stork 在 Argo 等完整但需要额外依赖且功能过于强大的 JSON 解析器和其他需要您类型可变、可 init
或剥夺您控制权的解析器之间找到了甜蜜的平衡。
它的工作原理
要从 JSON 转换到类型,您只需声明您想解析的字段。Stork 会为其推断类型并为您解析。为了实现这一点,您的类型 必须 遵循 FromJson
协议。
protocol FromJson {
static func from(value: JsonValue) -> Self?
}
在实践中,这意味着对于从 JSON 解析的类型,它需要提供从 JsonValue: string
、number
、bool
、JSON
或 [JsonValue
] 构造自身的方式。
在编译时,Storks 要求您想要从 JSON 获取的类型必须符合 FromJson
规范。否则,您在 Xcode 上会遇到以下编译错误消息
Generic parameter 'T' could not be infered
示例
假设我们想要从某些 JSON 输入中检索 User
类型的值,其中 User
及其嵌套类型如下定义
struct User {
let id: Int
let name: String
let email: String?
let country: Country?
let subscription: Subscription
let favouriteSongs: [Song]
}
enum Subscription: String {
case free
case bronze
case silver
case gold
}
enum Country: String {
case netherlands
case portugal
}
struct Song: Equatable {
let name: String
let band: String
}
有了 Stork,要将其从 JSON 转换为模型,我们只需确保这些类型符合我们的 FromJson
协议。
extension User: FromJson {
static func from(value: JsonValue) -> User? {
return value.ifObject { json in
User(
id: try json .! "id",
name: try json .! "name",
email: json .? "email",
country: json .? "country",
subscription: try json .! "subscription",
favouriteSongs: (json ..? "favouriteSongs") ?? []
)
}
}
}
// That's all you need for String/Int RawRepresentable Enums!
extension Subscription: FromJson {}
// Or you get to say how it's done!
// In this case, the country in JSON is short-coded and
// thus needs to be translated to the right Country case.
extension Country: FromJson {
static func from(value: JsonValue) -> Country? {
return value.ifString { str in
switch str {
case "nl": return .netherlands
case "pt": return .portugal
default: return nil
}
}
}
}
extension Song: FromJson {
static func from(value: JsonValue) -> Song? {
return value.ifObject { json in
Song(
name: try json .! "name",
band: try json .! "band"
)
}
}
}
现在我们已经有了所有东西,让我们看看 Stork 能为国家做出什么贡献
// Single user
let maybeUser: User? = User.from(json: userJSON)
// Array of users
let users: [User] = [User].from(jsonArray: usersJSON)
有关更多示例,请参阅 示例目录
安装
您可以通过以下方式将 Stork 添加为项目的依赖项。
CocoaPods
- 要使用 CocoaPods 将 Stork 添加到您的 Xcode 项目中,请在
Podfile
中添加以下行
pod 'StorkEgg', '0.2.1'
注意: pod 名称是 StorkEgg
,因为 Stork
已经被占用。
- 然后,让 CocoaPods 为您获取并安装它
pod install
- 最后,构建您的项目并导入 Stork
import Stork
Git Submodules
# Add Stork as a git submodule to your repository
git submodule add [email protected]:NunoAlexandre/stork.git
# Get the most updated version of Stork
git submodule update --remote
有关 Git Submodules 的更多信息,请参阅此处。
TODO
我计划支持 Carthage
和 Swift Package Manager
。
您的帮助将非常受欢迎!