函数式 JSON 解析器
功能
- 适用于 Linux
- 类型安全的 JSON 解析
- 函数值转换
- 易于解析嵌套值
- 无依赖
- 没有定义自定义操作符
要求
- Swift4.1 或更高版本
- OS X 10.9 或更高版本
- iOS 9.0 或更高版本
- watchOS 2.0 或更高版本
- tvOS 9.0 或更高版本
- Linux
安装
CocoaPods
将以下内容添加到您的 Podfile 中
use_frameworks!
target 'TargetName' do
pod 'Alembic'
end
Carthage
将以下内容添加到您的 Cartfile
github "ra1028/Alembic"
Swift Package Manager
将以下内容添加到您的 Package.swift
// swift-tools-version:4.0
let package = Package(
name: "ProjectName",
dependencies : [
.package(url: "https://github.com/ra1028/Alembic.git", .upToNextMajor(from: "3"))
]
)
示例
在示例中,解析以下 JSON
{
"teams": [
{
"name": "Team ra1028",
"url": "https://github.com/ra1028",
"members": [
{
"name": "Ryo Aoyama",
"age": 23
},
{
"name": "John Doe",
"age": 30
}
]
}
]
}
Any
, Data
或 String
类型的 JSON 对象创建 JSON 实例。
从 // from `Any` type JSON object
let json = JSON(object)
// from JSON Data
let json = try JSON(data: data)
// from JSON String
let json = try JSON(string: string)
从 JSON 中解析值
类型安全地解析值
let memberName: String = try json.value(for: ["teams", 0, "members", 0, "name"])
解析可选值
let missingText: String? = try json.option(for: "missingKey")
使用转换解析 JSON 中的值
使用各种单子函数进行值转换。
let teamUrl: URL = try json.parse(String.self, for: ["teams", 0, "url"])
.filterMap(URL.init(string:))
.value()
如果存在则转换可选值。
let missingUrl: URL? = try json.parse(String.self, for: "missingKey")
.filterMap(URL.init(string:))
.option()
从JSON到模型映射
所有符合Parsable
协议及其数组、字典都能被解析。
struct Member: Parsable {
let name: String
let age: Int
static func value(from json: JSON) throws -> Member {
return try .init(
name: json.value(for: "name"),
age: json.value(for: "age")
)
}
}
extension URL: Parsable {
public static func value(from json: JSON) throws -> URL {
guard let url = try URL(string: json.value()) else {
throw JSON.Error.dataCorrupted(value: json.rawValue, description: "The value was not valid url string.")
}
return url
}
}
struct Team: Parsable {
let name: String
let url: URL
let members: [Member]
static func value(from json: JSON) throws -> Team {
return try .init(
name: json.value(for: "name"),
url: json.value(for: "url"),
members: json.value(for: "members")
)
}
}
let team: Team = try json.value(for: ["teams", 0])
提示
Parsable
的类型。
默认符合JSON
String
Int
UInt
Double
Float
Bool
NSNumber
Int8
UInt8
Int16
UInt16
Int32
UInt32
Int64
UInt64
Decimal
Array where Element: Parsable
Dictionary where Key == String, Value: Parsable
Optional where Wrapped: Parsable
Parsable
使用初始化器符合struct Member: ParseInitializable {
let name: String
let age: Int
init(with json: JSON) throws {
name = try json.value(for: "name")
age = try json.value(for: "age")
}
}
使用参考文件
值转换的功能运算符
错误
更多示例
查看测试文件
游乐场
- 打开 Alembic.xcworkspace。
- 构建 Alembic (for Mac)。
- 在项目导航器中打开 Alembic 游乐场。
贡献
欢迎使用Fork并发起Pull Request!
在提交Pull Request之前,请确保您已经通过了包含的测试。如果您的Pull Request包括新功能,请为它编写测试案例。
许可证
Alembic采用MIT许可证发布。