tristanhimmelman / ObjectMapper

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

Custom Transform always returned nil #1094

Closed nbabaka closed 4 years ago

nbabaka commented 4 years ago

Your JSON dictionary:

{ "items":
[{
      "id": 74969,
      "product_id": 396,
      "content_id": 2412,
      "created_at": "2019-07-24 20:17:31",
}]
}

Your model:

class Purchase: Mappable {
    var id: Int!
    var contentId: Int! // content_id
    var productId: Int! // product_id
    var expired: Date!

    required init?(map: Map) {}

    func mapping(map: Map) {
            let transform = TransformOf<Date, String>(fromJSON: { (value: String?) -> Date? in
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            dateFormatter.timeZone = TimeZone(identifier: "UTC")
            let date = dateFormatter.date(from: value ?? "")
            return date
        }, toJSON: { (value: Date?) -> String? in
            if let date = value {
                let dateFormatter = DateFormatter()
                dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                return dateFormatter.string(from: date)
            }
            return nil
        })

        expired <- (map["real_expired_at"], transform)

    }
}

What you did:

let repo = Mapper<Purchase>().mapArray(JSONString: json["items"])

What you expected:

I expected something like:

Purchase(date: "some date object")

What you got:

Purchase(date: nil)

All other variables without custom transform are good.

nbabaka commented 4 years ago

oh (( XCODE debugger gave me wrong data (((