tristanhimmelman / ObjectMapper

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

How to create new independent object from keys in the top level json. #1112

Closed kwakueshun closed 4 years ago

kwakueshun commented 4 years ago

Your JSON dictionary:

{
  "name": "ObjectMapper",
  "url": "https://github.com/Hearst-DD/ObjectMapper",
  "aliasName: "ObjectMapperAlias",
  "aliasId: 2020,
}

Your model:

struct Repo: Mappable {
  var name: String!
  var url: URL!
  var alias: RepoAlias!

  init(_ map: Map) {
    name <- map["name"]
    url <- map["url"]
    alias <- ??
  }
}

struct RepoAlias: Mappable {
  var aliasName: String!
  var aliasId: URL!

  init(_ map: Map) {
    aliasName <- map["aliasName"]
    aliasId <- map["aliasId"]
  }
}

What you did:

let repo = Mapper<Repo>().map(myJSONDictionary)

What you expected:

I expected to have a way to do this but did not find documentation on this. Context, this would be easier to do if it was a nested object in the top json but it is not in this case but rather taking keys from the top level object to create another mappable object.

kwakueshun commented 4 years ago

Update: Doing this worked.

alias = Mapper<RepoAlias>().map(JSON: map.JSON)
kwakueshun commented 4 years ago

But I wonder if this has performance issues having to create Mapper<RepoAlias>() everytime and if there is a better way to do this.

kwakueshun commented 4 years ago

Update: Was able to do this without creating the Mapper

    func mapRelationShip<T: Mappable>(
        fromTopLevel map: Map,
        toAttributeWithKeyPath keyPath: ReferenceWritableKeyPath<Self, T?>
    ) {
        if let object = T.init(map: map) {
            self[keyPath: keyPath] = object
            self[keyPath: keyPath]?.mapping(map: map)
        }
    }