tristanhimmelman / ObjectMapper

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

Unable to map array objects with generic API Client #1102

Open najeeburrehman-brainx opened 4 years ago

najeeburrehman-brainx commented 4 years ago

Here is my APIClient:

func performRequest<T: Mappable>(_ request: HTTPRequest, withCompletion completion: @escaping (Result<T, CustomError>) -> Void) { 
      AF.request(request.endPoint, method: request.method, parameters: request.parameters, encoding: JSONEncoding(), headers: request.headers).responseJSON { response in
            switch response.result {
            case .success(let value):
                guard let model = Mapper<T>().map(JSONObject: value) else {
                    completion(.failure(CustomError(message:"Failed to parse data")))
                    return
                }
                completion(.success(model))
            case .failure(let error):
                completion(.failure(CustomError(message:"Something went wrong"))))
            }
        }
 }

My Model

struct Sleep: Mappable {

    var sleepStage: String?
    var duration: Int?
    var dateTime: String?

    init?(map: Map) {}

    mutating func mapping(map: Map) {
        sleepStage <- map["level"]
        duration <- map["seconds"]
        dateTime <- map["dateTime"]
    }

}

Works perfect for JsonObject as a response

{
   "level": "wake",
   "seconds": 30,
   "dateTime": "2020-05-05T22:48:30.000000Z"
}

The swift code works perfect to get the Sleep object.

APIClient.shared.performRequest(HTTPRequest()) { (response: Result<Sleep, CustomError>) in
           .........
 }

What I want to achieve

I also want the APIClient works for the array of JsonObjects i.e.

[
{
   "level": "wake",
   "seconds": 30,
   "dateTime": "2020-05-05T22:48:30.000000Z"
}, 
{
   "level": "wake",
   "seconds": 30,
   "dateTime": "2020-05-05T22:48:30.000000Z"
}
]

With my current implementation I can't call

APIClient.shared.performRequest(HTTPRequest()) { (response: Result<[Sleep], CustomError>) in
           .........
 }

Any help would be appreciated.

steve7688 commented 3 years ago

Hello @najeeburrehman-brainx did you resolve the problem you mentioned?Im a new Swifter

amoussa147 commented 2 years ago

Hello guys @najeeburrehman-brainx @steve7688, Were any of you able to check this issue out as I just started researching it :D