JSONtoCodable

Build Status CocoaPods MIT License CocoaPods Carthage compatible codecov

JSONtoCodable 是一个从原始 JSON 生成 Codable (Swift4) 代码的工具,使用 Swift4 编写。

Qiita: JSONからCodable化されたstructを自動生成するツールを作った話 - Qiita (日文文章,讲述了创建该工具的故事)

demo_macos.png

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
        }
    }
}

JaCo (macOS 应用)

demo_macos.png

jc (CLI 应用)

安装

$ brew tap YutoMizutani/jc
$ brew install jc

使用示例

$ curl https://httpbin.org/get | jc

或生成 .swift 文件,

$ curl https://httpbin.org/get | jc > Result.swift

帮助命令

$ jc -h

屏幕截图

demo_cli.png

支持的格式

转换

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)

查看更多: Config.swift

安装

Cocoapods

将此添加到您的 Podfile

pod 'JSONtoCodable'

并且

$ pod install

Carthage

将此添加到您的 Cartfile

github "YutoMizutani/JSONtoCodable"

并且

$ carthage update

许可证

JSONtoCodable 使用 MIT 许可证