/JSON-to-Swift-Converter

An Xcode editor extension to convert JSON format into Swift code.

Primary LanguageSwiftMIT LicenseMIT

JSON-to-Swift-Converter

An Xcode 9 editor extension to convert JSON format to Swift code.

Description

This is a lightweight naïve implementation for converting JSON-formatted text into Swift code. The JSON-formatted text structure and types are interpreted, and code is generated. Swift 4 Codable is supported.

There are several settings for controlling how the code is generated. By default, coding keys are declared, and properties and nested types are declared. The settings can be changed from the application that hosts the Xcode editor extension.

Separator characters (space, dash, and underscore) in JSON property names denote word boundaries, e.g., for a JSON property name "camel case", "camelCase" is generated for the corresponding Swift key name. Swift struct types are generated as substitutable with a "Type" suffix, for example, "<#CamelCaseType#>".

Example

The extension will convert the following JSON-formatted text:

{
    "currency": [
                 {
                 "symbol": "cp",
                 "coefficient": 0.01,
                 "long name": "copper piece",
                 "long name plural": "copper pieces"
                 },
                 {
                 "symbol": "sp",
                 "coefficient": 0.1,
                 "long name": "silver piece",
                 "long name plural": "silver pieces"
                 }
                ]
}

Into the following Swift implementation:

    private enum CodingKeys: String, CodingKey {
        let symbol
        let longNamePlural = "long name plural"
        let currency
        let longName = "long name"
        let coefficient
    }

    struct <#CurrencyType#>: Codable {

        let longNamePlural: String!
        let coefficient: Double!
        let symbol: String!
        let longName: String!

    }

    let currency: [<#CurrencyType#>]!

Usage

In Xcode, choose Editor > Convert JSON to Swift > Convert JSON to Swift.

Settings

In Xcode, choosing Editor > Convert JSON to Swift > Settings... opens the host application where settings that control the conversion can be changed. Settings include:

  • declaration: specify let or var for property declarations (default is let)
  • typeUnwrapping: options include explicit, optional ("?"), or required ("!") (default is required)
  • supportCodable: whether to provide and init(from:) and encode(to:) function (default is true)
  • addDefaultValue: whether to add default values, e.g., "= 0" (default is false)
  • addInitAndDictionary: whether to add an init(from:) method and dictionary: variable accessor (default is false)

Credits

This extension is loosely based on Json2Property, which in turn is based on ESJsonFormat-Xcode. This version is written entirely Swift, is expanded a bit, and has unit tests.