tristanhimmelman / ObjectMapper

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

Class member array of mappables isn't getting serialized. #1024

Closed widavies closed 5 years ago

widavies commented 6 years ago

Your model:

class RForm : Mappable {

    public var pit:[RMetric]?;
    public var match:[RMetric]?;

    required init?(map: Map) {

    }

    init(pit:[RMetric], match:[RMetric]) {
        self.pit = pit;
        self.match = match;
    }

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

class RMetric : Mappable {

    public var ID: Int?;
    public var title: String?; 
    private var modified: Bool?; 

    required init?(map: Map) {}

    init(ID: Int, title: String) {
        self.ID = ID;
        self.title = title;
        self.modified = false;
    }

    public func getFormDescriptor() -> String {
        preconditionFailure("This method must be overriden by its children");
    }

    public func clone() -> RMetric {
        preconditionFailure("This method must be overriden by its children");
    }

    public func isModified() -> Bool {
        return modified!;
    }

    public func toString() -> String {
        preconditionFailure("This method must be overriden by its children");
    }

    // This defines how things get mapped to and from JSON
    func mapping(map: Map) {
        ID <- map["ID"];
        title <- map["title"];
        modified <- map["modified"];
    }

}

}

What you did:

let form = RForm(pit: [text2], match: match);
let JSONString = Mapper().toJSONString(form, prettyPrint: true);
print(JSONString)

What you expected:

I expected a JSON output of RForm

What you got:

print(JSONString) just prints nil

JackIrish commented 5 years ago

@wdavies973 Did you end up getting this to work? Running into a similar issue.

widavies commented 5 years ago

@JackIrish no, haven't been able to get it to work.

gcharita commented 5 years ago

Seems to work just fine (tested in Xcode 9.4.1 and 10.1) screenshot 2019-01-16 at 13 07 43

npalamar commented 5 years ago

The same problem (swift 5, iOS 12). If array type isn't nill = all fine. Works:

final class MarketMap: ImmutableMappable {

    let outcomes: [OutcomeMap]

    required init(map: Map) throws {
        do {
            outcomes = try map.value("outcomes")
        }  catch let error {
            print(error)
            throw error
        }
    }
}

NOT Works:

final class MarketMap: ImmutableMappable {

    let outcomes: [OutcomeMap]?

    required init(map: Map) throws {
        do {
            outcomes = try? map.value("outcomes")
        }  catch let error {
            print(error)
            throw error
        }
    }
}
tristanhimmelman commented 5 years ago

I believe this has been addressed in the latest release