I am trying to map the json to model in Swift using JSONModel.
Everything works if model doesn't have properties that are JSONModel subclasses.
So in example this works, and it maps the properties successfully:
class Person: JSONModel {
var name: NSString?
var gender: NSString?
}
But if I put JSONModel subclass City, this property is not initialized, and it crashes the app when I try to access the city property later (I can successfully access person.name, and person.gender, but on person.city it crashes without any info):
class Person: JSONModel {
var name: NSString?
var gender: NSString?
var city: City? // City is JSONModel subclass
}
It looks like JSONModel cannot map/parse property if it is a JSONModel subclass. Did anyone experienced this and solved it?
JSONModel does not work in Swift, that's why you're having issues. From the JSONModel readme:
NB: Swift works in a different way under the hood than Objective-C. Therefore I can't find a way to re-create JSONModel in Swift. JSONModel in Objective-C works in Swift apps through CocoaPods or as an imported Objective-C library.
You might be able to get it working in certain edge cases - but the only reliable way to use it, is by writing Objective C code against it, and using these Objective C classes. If you'd like to do pure Swift, you should look at other libraries such as Argo and a bunch of others.
Actually the problem with JSONModel in Swift is as follows:
It uses Objc-runtime for understanding what type is each property and as soon as you declare a type which Obj-c runtime does not know how to map, then JSONModel can only map it as a String .........or NSNumber if you know that you have a numeric field.
The way it works: So basically if you declare all the properties that remain nil in your case as Strings, you'll start seeing values. The same works if you declare numeric fields as NSNumber. Both String and NSNumber can be also declared as optionals with no specific problem for JSONModel.
But dare you not to use the primitive types from Swift with optional declaration (Int?, Double?, Bool?). This will not work.
What will work is avoiding by any means declaring as optionals by:
1) var tmpInt : Int = 0, giving a default value
2) var tmpInt : Int!, forcing
Of course these last "workarounds" are totally against why Swift appeared in this world, but this is how you bring the old Objective-C habits in the new modern Swift (;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With