JSONtoCodable 是一个从原始 JSON 生成 Codable (Swift4) 代码的工具,使用 Swift4 编写。
Qiita: JSONからCodable化されたstructを自動生成するツールを作った話 - Qiita (日文文章,讲述了创建该工具的故事)
从 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
}
}
}
$ brew tap YutoMizutani/jc
$ brew install jc
$ curl https://httpbin.org/get | jc
或生成 .swift 文件,
$ curl https://httpbin.org/get | jc > Result.swift
$ jc -h
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)
将此添加到您的 Podfile
pod 'JSONtoCodable'
并且
$ pod install
将此添加到您的 Cartfile
github "YutoMizutani/JSONtoCodable"
并且
$ carthage update
JSONtoCodable 使用 MIT 许可证。