Json_serializable.dart: Json_serializable type cast issue

Created on 1 May 2019  路  2Comments  路  Source: google/json_serializable.dart

Dart VM version: 2.3.0-dev.0.3 (Tue Apr 23 12:02:59 2019 -0700) on "macos_x64"
Using:
https://pub.dartlang.org/packages/build_runner ^1.3.5
https://pub.dartlang.org/packages/json_serializable ^2.2.2

for a property like:
final double limitSpending;
in the .g.dart it generates
limitSpending: (json['limitSpending'] as num)?.toDouble(),
I feel like the right cast should be:
limitSpending: double.parse(json['limitSpending']),
otherwise the type cast error is showing:
"type 'String' is not a subtype of type 'num' in type cast"

similar for int
final int weekDay;
-> .g.dart
weekDay: json['weekDay'] as int);
-> should be
weekDay: int.parse(json['weekDay'])
-> else error
"type 'String' is not a subtype of type 'int' in type cast"

similar for bool
final bool canJoin;
-> .g.dart
canJoin: json['canJoin'] as bool,
-> should be
canJoin: json['canJoin'] == 'true' ? true : false
-> else error
"type 'String' is not a subtype of type 'bool'"

Most helpful comment

Of course I do that. Just saying, you can do the cast a bit better as APIs are not perfect and not all of them returns the right type.
Thanks.

All 2 comments

We're set up to handle the correct literals coming from json.

So we assume

{"number": 42, "bool": true}

Not

{"number": "42","bool": "true"}

You can always use custom converters with toJson and fromJson if you want to handle string input, though.

Of course I do that. Just saying, you can do the cast a bit better as APIs are not perfect and not all of them returns the right type.
Thanks.

Was this page helpful?
0 / 5 - 0 ratings