tristanhimmelman / ObjectMapper

Simple JSON Object mapping written in Swift
MIT License
9.15k stars 1.03k forks source link

How to map multiple JSON properties to another realm model in the current model? #1034

Closed wakaryry closed 5 years ago

wakaryry commented 5 years ago

Your JSON dictionary:

{
  "userName": "Jack",
  "id": 10086,
  "userID": 123,
  "content": "This is an album content!"
  "userAvatar": "https://useravatarurl.png"
}

The userName userID userAvatar are for the owner of the album, which are in UserModel. The id content are for album.

Your model:

The model is RealmSwift Object Model:

class UserModel: Object, Mappable {
  var id = 0
  var userName: String = ""
  var avatarUrl: String?

  init(_ map: Map) {
    id <- map["id"]
    avatarUrl <- map["avatar"]
    username <- map["userName"]
  }
}

class AlbumModel: Object, Mappable {
  var id = 0
  var content: String = ""
  var owner: UserModel?

  init(_ map: Map) {
    id <- map["id"]
    content <- map["content"]
    // owner <- map["id"] ?? How could I map userID, userName, userAvatar into a realm object?
  }
}

Thanks for any help.

wakaryry commented 5 years ago

I think I have got my answer. What I need is to map the json twice, one for AlbumModel, and the other for UserModel. In AlbumModel, I map the userID in json into UserModel-type property owner.