Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A little help with nested objects needed #114

Closed
pfitz opened this issue Apr 29, 2015 · 3 comments
Closed

A little help with nested objects needed #114

pfitz opened this issue Apr 29, 2015 · 3 comments

Comments

@pfitz
Copy link

pfitz commented Apr 29, 2015

I need a little guidance with mapping nested objects. I managed to use ObjectMapper with built in types perfect. But how do I map nested custom objects?

Given something like this:

class A {
    let b: B
    let c: [C]
}

As I said I managed to map B and C alone. But how do I map it from inside A? Do I need to write a custom transform? Or do I need to make B and C conform to some protocol? I am guessing it is quite simple but I just can't get my head around it.

@tristanhimmelman
Copy link
Owner

Here is an example from the tests included in the framework. The key is that any nested objects also need to conform to the Mappable protocol. Also, by default ObjectMapper does not support immutable types (let) as member variables.

Hope this helps

class Plan: Mappable {
    var primaryTask: Task?
    var tasks: [Task]?

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        tasks <- map["tasks"]
    }
}

class Task: Mappable {
    var taskId: Int?
    var percentage: Double?

    init() {}

    required init?(_ map: Map) {
        mapping(map)
    }

    func mapping(map: Map) {
        taskId <- map["taskId"]
        percentage <- map["percentage"]
    }
}

@pfitz
Copy link
Author

pfitz commented Apr 29, 2015

Ah ok. Did not believed it to be THAT easy. With Mantle you had to say which class is should map to. It is working. Thanks!!!

@pfitz pfitz closed this as completed Apr 29, 2015
@tristanhimmelman
Copy link
Owner

Glad to help 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants