JSONtoCodable 是一个从原始 JSON 生成 Swift 4 编码可序列化文本的工具,用 Swift 4 编写。
Qiita: 制作了一个自动生成从 JSON 遵循的 struct 的工具 - Qiita
TL;DR
从 JSON
{
"user": {
"Name": "Yuto Mizutani"
},
"lib": {
"lib-name": "JSONtoCodable",
"year": 2018,
"version": "1.0.2",
"released": "2018-09-22"
},
"text": "Hello, world!!"
}
转为 Codable。
public struct Result: Codable {
public let user: User
public let lib: Lib
public let text: String
public struct User: Codable {
public let name: String
private enum CodingKeys: String, CodingKey {
case name = "Name"
}
}
public struct Lib: Codable {
public let libName: String
public let year: Int
public let version: String
public let released: String
private enum CodingKeys: String, CodingKey {
case libName = "lib-name"
case year
case version
case released
}
}
}
示例
支持的格式
- 类型
- 字符串
- 布尔值
- 整数
- 双精度浮点数
- 结构体(s)
- 可选
- 数组
- 数组开始
- 多重数组
- 数组对象
- 可选数组
- 嵌套数组和对象的数量
- 无限
- 输入 JSON 中的空格数
- 0 到无限
翻译
JSON 值 | Swift 类型 |
---|---|
"text" | 字符串 |
true | 布尔值 |
-10 | 整数 |
1.0 | 双精度浮点数 |
null | <Foo>? |
(其他) | Any |
用法
import JSONtoCodable
let json: String = """
{
"Hello": "Hello, world!!"
}
"""
let jsonToCodable = JSONtoCodable()
let codable = try? jsonToCodable.generate(json)
print(codable)
/*
struct Result: Codable {
let hello: String
private enum CodingKeys: String, CodingKey {
case hello = "Hello"
}
}
*/
配置
let config = Config()
config.name = "Result" // struct Result: Codable {}
config.accessModifier = AccessModifier.public // public struct
config.caseType = (variable: CaseType.camel, struct: CaseType.pascal)
config.lineType = LineType.lineFeed
config.indentType = IndentType.space(4)
安装
Cocoapods
将以下代码添加到您的 Podfile
pod 'JSONtoCodable'
并
$ pod install
Carthage
将以下代码添加到您的 Cartfile
github "YutoMizutani/JSONtoCodable"
并
$ carthage update
授权
JSONtoCodable 在 MIT授权 之下可用。