swift codgen not decoding json array responses
There appears to be missing decoders for array responses in Decoders.initialize().
For example, an api that returns Response<[Employee]> will fail to decode unless I add the following line to Decoders,initialize:
Decoders.addDecoder(clazz: [Employee].self) { return decode(clazz: [Employee].self, source: $0) }
I believe the issue is related to generic types in swift. For example, suppose T1 = [T2]. Then given the following two method signatures:
decode<T>(clazz clazz: [T].Type, source: AnyObject) -> [T]
decode<T>(clazz clazz: T.Type, source: AnyObject) -> T
swift will choose the second function for T=T1 and the first function for T=[T2], which may not be expected.
note that this problem does not exist for arrays nested inside json objects, only root json array responses.
@tigaris Thanks for reporting the issue. May I know if you've cycle to help contribution the fix?
Ref: https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution
@wing328 sure I can contribute fix.
This should be already fixed by #1548.
i see the fix in github, not being used at https://generator.swagger.io yet i guess.
I think this is not fixed yet:
I did:
- git clone https://github.com/swagger-api/swagger-codegen.git
- cd swagger-codegen
- in Podspec.mustache I added:
s.tvos.deployment_target = '9.1' - man package
I use the following command snipet to build the client: java -jar ~/GitHub/swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar ....
Our API response is an JSON array like:
[
{
"key":"value",
"key":"value"
},
{
"key":"value",
"key":"value"
}
]
running the client brings an exception: Could not cast value of type '__NSCFDictionary' (0x11082fef8) to 'NSArray' (0x11082f908).
in Models.swift line:
static func decode<T>(clazz clazz: [T].Type, source: AnyObject) -> [T] {
let array = source as! [AnyObject]
return array.map { Decoders.decode(clazz: T.self, source: $0) }
}
@tannhaeuser could you share what your actual json schema for the array looks like?
I just got feedback from our developers. It turns out that the API was responding:
HTTP: 200 but a JSON like this:
{ "status": "500" "message": "something" }
which did not fit to the data model of this specific swagger api. That happened because of wrong parameter value in API request. After fixing it everything is fine now. Only thing to mention is that we should try to avoid that the Swagger API client crashed the App with this kind off exception in case Response does not match to model.
This issue can be closed
@tannhaeuser yes, ideally the swift API client should throw an ApiException to report the deserialization error.
May I know if you've cycle to make the improvement to the Swift API client?
Ref: https://github.com/swagger-api/swagger-codegen/blob/master/CONTRIBUTING.md