Skip to content

Instantly share code, notes, and snippets.

@rchatham
Created September 1, 2020 17:23
Show Gist options
  • Save rchatham/ca3bbb88b5a760a9064b3333b113dbc7 to your computer and use it in GitHub Desktop.
Save rchatham/ca3bbb88b5a760a9064b3333b113dbc7 to your computer and use it in GitHub Desktop.
A SwiftyJSON template file for models generated using JSONCafe
import Foundation
import SwiftyJSON
class {{className}}: Codable {
{{#properties}}
var {{nativeName}}: {{type}}
{{/properties}}
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(json: JSON) {
{{#properties}}
{{!-- Start Array Handling --}}
{{#xif "isArray"}}
{{#xif "elementsAreOfCustomType"}}
{{nativeName}} = [{{elementType}}]()
let {{nativeName}}Array = json["{{jsonName}}"].arrayValue
for {{nativeName}}Json in {{nativeName}}Array{
let value = {{elementType}}(fromJson: custArrayJson)
custArray.append(value)
}
{{else}}
{{nativeName}} = [Int]()
let {{nativeName}}Array = json["{{jsonName}}"].arrayValue
for {{nativeName}}Json in {{nativeName}}Array{
{{nativeName}}.append({{nativeName}}Json.{{basicType}})
}
{{/xif}}
{{!-- End Array handling --}}
{{else}}
{{#xif "isCustomClass"}}
{{nativeName}} = {{capitalizeVarType}}(json: json["{{jsonName}}"])
{{else}}
{{!-- Handling basicType --}}
{{#xif "basicType"}}
{{nativeName}} = json["{{jsonName}}"].{{basicType}}
{{else}}
{{nativeName}} = json["{{jsonName}}"]
{{/xif}}
{{!-- End Handling basicType --}}
{{/xif}}
{{/xif}}
{{/properties}}
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> [String:Any]
{
var dictionary = [String:Any]()
{{#properties}}
{{#xif isCustomClass}}
{{!--Custom type--}}
dictionary["{{nativeName}}"] = {{nativeName}}.toDictionary()
{{else}}
{{#xif "isArray && elementsAreOfCustomType"}}
{{!-- Array Type --}}
var dictionaryElements = [[String:Any]]()
for {{nativeName}}Element in {{nativeName}} {
dictionaryElements.append({{nativeName}}Element.toDictionary())
}
dictionary["{{nativeName}}"] = dictionaryElements
{{else}}
{{!-- Default Type --}}
dictionary["{{jsonName}}"] = {{nativeName}}
{{/xif}}
{{/xif}}
{{/properties}}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
private enum CodingKeys: String, CodingKey {
{{#properties}}
case {{nativeName}} = "{{jsonName}}"
{{/properties}}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment