JSON Cafe Custom Template
Custom Template
http://www.jsoncafe.com/
http://www.jsoncafe.com/
import Foundation
import SwiftyJSON
import RealmSwift
class {{className}} : Object {
{{#properties}}
{{#if isArray}}
var {{nativeName}}List: List<{{cleanType}}> = List<{{cleanType}}>()
{{else}}
{{#xif "type === 'Int' || type === 'Float'"}}
@objc dynamic var {{nativeName}} : {{type}} = 0
{{else}}
@objc dynamic var {{nativeName}} : {{type}}?
{{/xif}}
{{/if}}
{{/properties}}
override public static func primaryKey() -> String? {
return "identifier"
}
public static func with(realm: Realm, json: JSON) -> {{className}}? {
let identifier = json["id"].intValue
if identifier == 0 {
return nil
}
var obj = realm.object(ofType: {{className}}.self, forPrimaryKey: identifier)
if obj == nil {
obj = {{className}}()
obj?.identifier = identifier
} else {
obj = {{className}}(value: obj!)
}
{{#properties}}
{{#if isCustomClass}}
if json["{{jsonName}}"].exists() {
obj?.{{nativeName}} = {{type}}.with(json: json["{{jsonName}}"])
}
{{else}}
{{#if isArray}}
if json["{{jsonName}}"].exists() {
obj?.{{nativeName}}List.removeAll()
for itemJson in json["{{jsonName}}"].arrayValue {
if let item = {{cleanType}}.with(json: itemJson) {
obj?.{{nativeName}}List.append(item)
}
}
}
{{else}}
{{#if basicType}}
if json["{{jsonName}}"].exists() {
{{#xif "type === 'String'"}}
obj?.{{nativeName}} = json["{{jsonName}}"].string
{{else xif "type === 'Float'"}}
obj?.{{nativeName}} = json["{{jsonName}}"].doubleValue
{{else}}
obj?.{{nativeName}} = json["{{jsonName}}"].{{basicType}}
{{/xif}}
}
{{else}}
if json["{{jsonName}}"].exists() {
obj?.{{nativeName}} = json["{{jsonName}}"]
}
{{/if}}
{{/if}}
{{/if}}
{{/properties}}
return obj
}
public static func with(json: JSON) -> {{className}}? {
return with(realm: try! Realm(), json: json)
}
}