How should I assign my data models to map the JSON using Alamofire?
Add a method to convert from FriendModel to UserModel:
struct UserModel {
init(friend: FriendModel) {
id = friend.id
userFirstName = friend.firstName
userSurname = friend.lastName
... // assign all the other fields as needed
}
}
Then use it to convert your results:
friendsAPI.getFriends { [weak self] apiFriends in
self?.friends0 = apiFriends.map({ UserModel(friend: $0) })
}
Here it is an init method, but feel free to put it in a normal func like func userFromFriend(_ friend: FriendModel) -> UserModel
, and put that func wherever you want.
Realm `description` property behaving differently to other properties
By creating a description
property, you're overriding the -description
method on NSObject that's used to print an object's contents when using NSLog
or println
.
See https://stackoverflow.com/a/4718806/373262 for more details.
Realm create() cannot parse JSON string to NSDate?
That's correct. You cannot take a String
containing a date and automatically map it to an NSDate
property in Realm.
The easiest way to get around this, would be to deserialize your JSON data into a mutable dictionary, and then manually replace that specific String
property with an NSDate
value, generated from a NSDateFormatter
object. Once that's done, you should be able to simply pass the dictionary to Realm to create the new Object
in it.
This was previously discussed in a Realm GitHub issue: https://github.com/realm/realm-cocoa/issues/605
Nested Arrays throwing error in realm.create(value: JSON) for Swift
Unfortunately you can't just setup your Requirements
model in a different way, which would allow you to directly map your JSON to Realm objects.
The init(value: AnyObject)
initializer expects either a dictionary, where the keys are the names of your object properties, or an array, where the property values are ordered in the same like they are defined in your object model. This initializer is recursively called for related objects.
So to make that work, you will need to transform your JSON, so that you nest the string values into either dictionaries or arrays. In your specific case you could achieve that like seen below:
…
var jsonDict = json as! [String : AnyObject]
jsonDict["requirements"] = jsonDict["requirements"].map { ["value": $0] }
let exhibit = Exhibit(value: jsonDict)
…
Side Note
I'd recommend using singular names for your Realm model object classes (here Requirement
instead Requirements
) as each object just represent a single entity, even if you use them only in to-many relationships.
How to map a realm list of custom objects using Mappable protocol in Swift
Having a look at one of the Issues page on ObjectMapper's GitHub repo, it doesn't look like Realm List
objects are properly supported yet.
That issue also lists a potential workaround for getting it to work for the time being, which I'll mirror here:
class MyObject: Object, Mappable {
let tags = List<Tag>()
required convenience init?(_ map: Map) { self.init() }
func mapping(map: Map) {
var tags: [Tag]?
tags <- map["tags"]
if let tags = tags {
for tag in tags {
self.tags.append(tag)
}
}
}
}
Realm + Swift, nested JSON
In your JSON, ageRange
is a dictionary, whereas the UserObject.ageRange
property is a List<AgeRangeObject>
. You have mismatched models.
You either need to update your models to reflect the structure of your JSON:
var ageRange = List<AgeRangeObject>()
becomes
dynamic var ageRange: AgeRangeObject? = nil
or vice versa, update your JSON to reflect the structure of your models:
{
"gender" : "male",
"id" : "123456789",
"age_range" : [{
"min" : 21
}],
"last_name" : "LastName"
}
Related Topics
iOS 14 Widget Detect System Theme Change
Swift Ensembles Set Up & Ubiquitycontaineridentifier
Protocol Variable Implementing Another Protocol
Uisearchcontroller Hiding Status Bar on iOS 11 Swift 4
Given a Swift 'Any' Type How to Determine If It's an 'Optional'
Characteristic.Value from Bluetooth Reading in Swift
Why Does Editing a Textfield Throw a Nsinvalidargumentexception
Swift: Right/Left Click on Nsstatusbar
Why I Can't Access My 3Rd Level Coredata Data in Swift
Redirect Process Stdout to Apple System Log Facility in Swift
Swift Spritekit Get Visible Frame Size
Swift: How to Get Image Name from Assets
Sharing Screenshot of Swiftui View Causes Crash
Turn Off Splash Screen When Using Flutterviewcontroller Within Existing Native App