An Xcode 9 editor extension to convert JSON format to Swift code.
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#>".
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#>]!
In Xcode, choose Editor
> Convert JSON to Swift
> Convert JSON to Swift
.
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
: specifylet
orvar
for property declarations (default islet
)typeUnwrapping
: options includeexplicit
,optional
("?"), orrequired
("!") (default isrequired
)supportCodable
: whether to provide andinit(from:)
andencode(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)
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.