tristanhimmelman / AlamofireObjectMapper

An Alamofire extension which converts JSON response data into swift objects using ObjectMapper
MIT License
2.66k stars 474 forks source link

Generic Structs #239

Closed aliiizzz closed 5 years ago

aliiizzz commented 6 years ago

hello, i have a Json like this: { "data": [ { "id": 54, "title": "test", "cities": { "data": [ { "id": 55, "title": "test" }, { "id": 56, "title": "test" } ] } } ] } and i am trying to map this with generics because i have many responses like this tha contain data object. i have a struct like this:

 import ObjectMapper
 struct ServiceResponse<T> : Mappable {
    var response: [T]?
    init?(map: Map) {
    }
    mutating func mapping(map: Map) {
        response <- map["data"]
    }
 }

but it is always nil, if i use specific type instead of T it works like charm. any suggestions?

mdathersajjad commented 6 years ago

Same problem. My JSON is a generic response object {"succes":"true","errorMessage":"Message","data": "[]/{}" }. So i created a generic class as @aliiizzz . All other fields are mapping except data. It is always nil.

gcharita commented 6 years ago

Generic type T should implement Mappable protocol.

So, simply use the following struct instead and it will work:

import ObjectMapper
struct ServiceResponse<T: Mappable> : Mappable {
    var response: [T]?
    init?(map: Map) { }
    mutating func mapping(map: Map) {
        response <- map["data"]
    }
}