swagger-api / swagger-codegen

swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.
http://swagger.io
Apache License 2.0
17.02k stars 6.03k forks source link

[Swift 4] Property with type 'Any' does not conforms with codable protocol #6483

Open vntguca opened 7 years ago

vntguca commented 7 years ago
Description

Current code generator for Swift 4 generates invalid code for JSON dictionaries or properties with object value type.

Property generated code:

open class TaskParameter: Codable {

    public var id: String?
    public var value: Any?

    public init() {}

}

Dictionary generated code:

open class EntityKey: Codable {
    public var entity: String?
    public var alias: String?
    public var fields: [String:Any]?

    public init() {}
} 
Swagger-codegen version

2.2.3

Swagger declaration file content or url
"definitions": {
"TaskParameter": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                },
                "value": {
                    "type": "object"
                }
            }
        },
"EntityKey": {
            "type": "object",
            "properties": {
                "entity": {
                    "type": "string"
                },
                "alias": {
                    "type": "string"
                },
                "fields": {
                    "type": "object",
                    "additionalProperties": {
                        "type": "object"
                    }
                }
            }
        }
}
Command line used for generation

swagger-codegen generate -i ./swagger.json -l swift4 -o ./api

Steps to reproduce

Generate the code with swagger-codegen 2.2.3 then try to compile the generated classes on Xcode 9 GM or any beta version.

Related issues/PRs
Suggest a fix/enhancement

Seems like this problem relies on the fact that Any is not (and will be not) Codable, thus a generic "AnyCodable" that conforms to this protocol should be used instead.

StackOverflow Discussion Apple Forum Discussion

alexandrutomescu commented 6 years ago

I've been having the same issue with swift3 and swift4 generated code, in XCode Version 9.1 (9B55). I now see that the code generated by editor.swagger.io is closer to correct, for swift4.

For this minimal example from OpenAPI I get three errors in the generated file CodableHelper.swift (this is about swift4).

line 19: decoder.dataDecodingStrategy = .base64Decode. Error: Type 'JSONDecoder.DataDecodingStrategy' has no member 'base64Decode' Solution: decoder.dataDecodingStrategy = .base64

line 39: encoder.dataEncodingStrategy = .base64Encode Error: Type 'JSONEncoder.DataEncodingStrategy' has no member 'base64Encode' Solution: encoder.dataEncodingStrategy = .base64

line 38: encoder.outputFormatting = (prettyPrint ? .prettyPrinted : .compact) Error: Type of expression is ambiguous without more context Solution: encoder.outputFormatting = .prettyPrinted [I don't know if this is what's intended here]

What is the status, is anybody working on this? Any estimate on when it will be fixed?

alexandrutomescu commented 6 years ago

In fact, my json is more complex than my above example, and I'm still getting errors such as: Type 'HttpResponse' does not conform to protocol 'Decodable'. This class has some members of custom types, for example: public var httpContext: HttpContext? Are these custom objects the problem?

Even for more basic classes I'm getting similar errors. For example, for

//
// KeyValuePairTypeObject.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//

import Foundation

open class KeyValuePairTypeObject: Codable {

    public var key: String?
    public var value: Any?

    public init() {}

}

I'm getting Type 'KeyValuePairTypeObject' does not conform to protocol 'Decodable' Type 'KeyValuePairTypeObject' does not conform to protocol 'Encodable'

Is it because of the member of type Any ?

What is the status, is anybody working on this? Any estimate on when it will be fixed?

Basically, at the moment we cannot get any running code at all, all code generated for swift3, swift4 and objective-c has strange errors such as these.

xiaochow commented 6 years ago

@alexandrutomescu the same issue has occurred in the project I'm currently working on and I have been waiting for this to get fixed. It is because Any is a primitive type in Swift so it's not codable, which makes your whole class not codable.

A temporary workaround would be manually replace type Any with codable generics in your generated Swift code to get your project to run.

In your example, the original code:

open class KeyValuePairTypeObject: Codable {

    public var key: String?
    public var value: Any?

    public init() {}

}

could be changed to:

open class KeyValuePairTypeObject<T: Codable>: Codable {

    public var key: String?
    public var value: T?

    public init() {}

}
danwoodel commented 5 years ago

Hey guys, We have a fix for this, will raise a PR.

antonybrro commented 5 years ago

@danielwoodel just want to remind about this issue. Our team looking forward for solution =)

jmtaillant commented 5 years ago

Any update on this?

danwoodel commented 5 years ago

Hey @jmtaillant, Yes sorry took some extra time because we wanted to test it vigiriously in our solution. It all looks good @wuf810 can we create a fork to your account and raise a PR. @wuf810 I think our branch contains a few fixes so we need 2 PRs. I think one was a date/time issue and this issue. They should not be related but I think they are in the same branch at the moment.

@jmtaillant Me and @wuf810 will let you know when we have created a PR Ill create a ticket in our jira board to factor it into a sprint.

goors commented 4 years ago

Any update on this maybe?

danwoodel commented 4 years ago

Hi we have fixed this and we have been running on our own branch we return to work this week we will raise a pr next week if that weeks for you.

On 30 Dec 2019 21:10, Nikola notifications@github.com wrote:

Any update on this maybe?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHubhttps://github.com/swagger-api/swagger-codegen/issues/6483?email_source=notifications&email_token=AMGC5BRZQSDWMPBLBBAMZDTQ3JPULA5CNFSM4D2WFPQ2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEH3GXPQ#issuecomment-569797566, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AMGC5BTBABBRO5VY3ERCVQ3Q3JPULANCNFSM4D2WFPQQ.

ghost commented 4 years ago

Has the PR been raised yet? Any update on this?

HugoMario commented 4 years ago

@sy-tech , no really. I'm not familiar with swift. But if you are willing to propose a PR, ping me and i can help you to get it merged.

ghost commented 4 years ago

I actually dont know swift either, im just trying to build a client with it as an example. But i did some adjustments to my open api doc and it looks like this issue is gone.

Edit: The changes to swagger did not fix it. So i am still looking into it

cerupcat commented 4 years ago

@danielwoodel any updates on this? This appears to still be an issue. Where can I find your branch with a solution?

alldne commented 3 years ago

Until the changes to be released, you can resolve it by adding --type-mappings object=JSONValue as a workaround.

e.g.

swagger-codegen generate -i your-swagger.json -l swift5 -o output-dir --template-dir template-dir --template-engine handlebars --type-mappings object=JSONValue
2jumper3 commented 7 months ago

I'm still at this same problem, nothing work )

codegen line: swagger-codegen generate -i https://.... -l swift5 -o /Users/sergejudalov/Developer/alfabit-wallet-ios/alfawalletCustody --type-mappings object=JSONValue

public struct AdminWithdrawSymbolRequest: Codable {
    public var address: Any
    public var symbol: Any
    public var bchCode: Any?
    public var tag: Any?
    public var amount: Any
    public var otp: Any?

Can it be because of a bad Swagger file?

"AdminWithdrawSymbolRequest":{"properties":{"address":{"type":"string","title":"Address"},"symbol":{"type":"string","title":"Symbol"},"bch_code":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Bch Code"},"tag":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Tag"},"amount":{"type":"string","title":"Amount"},"otp":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Otp"}},"type":"object","required":["address","symbol","amount"],"title":"AdminWithdrawSymbolRequest"}

Everything Any

Screenshot 2024-03-25 at 13 45 47