Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Dart] Number decoded to int causes an exception when assigning to double #9808

Closed
MichaelMarner opened this issue Oct 28, 2019 · 0 comments · Fixed by #9809
Closed

[Dart] Number decoded to int causes an exception when assigning to double #9808

MichaelMarner opened this issue Oct 28, 2019 · 0 comments · Fixed by #9809

Comments

@MichaelMarner
Copy link
Contributor

Description

Suppose you have an API Model containing a double property, swagger-codegen will generate a class similar to this:

class ApiResponse {
  double ttl = null;
  
  LoginResponse.fromJson(Map<String, dynamic> json) {
    if (json == null) return;

    ttl =
        json['ttl']
    ;
  }
}

This works fine, as long as the JSON returned from the API includes a decimal place, for example:

{
  "ttl": 21.1
}

However, If the API returns a value that contains no decimal place, Dart's JsonCodec will parse this as an int. The Model's fromJson method will then throw an exception, as an int cannot be assigned to a double.

An API returning the following:

{
  "ttl": 21
}

Will be parsed by JsonCodec an int, and will then throw the following exception when attempting to assign it to ApiModel.ttl:

_TypeError (type 'int' is not a subtype of type 'double')
Swagger-codegen version

2.48 (compiled from 31e7ea9)

Swagger declaration file content or url

N/A

Command line used for generation

N/A

Steps to reproduce

N/A

Related issues/PRs

N/A

Suggest a fix/enhancement

To assign to a double, the value parsed from the json should be explicitly cast to a double before assigning. This works as all Dart's number types have a toDouble method.

MichaelMarner added a commit to MichaelMarner/swagger-codegen that referenced this issue Oct 28, 2019
MichaelMarner added a commit to MichaelMarner/swagger-codegen that referenced this issue Oct 28, 2019
HugoMario added a commit that referenced this issue Dec 15, 2020
This was referenced Mar 11, 2021
This was referenced Mar 11, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant