google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.54k stars 392 forks source link

Decimal, API and SQLite #1421

Closed alexrosabr closed 2 months ago

alexrosabr commented 2 months ago

FromJson

The generated code uses as String but when the data comes from the API it fails with:

type 'double' is not a subtype of type 'String' in type cast

If I edit the generated code to use .toString() instead, it works.

ToJson

The generated code does not work with SQLite; the warning message says it will allow it for now but the warning may become an error in the future.

If I edit the generated code to use ?.toDouble() it works.

Edited code (to make it work)

ApiPdvTroco _$ApiPdvTrocoFromJson(Map<String, dynamic> json) => ApiPdvTroco()
  ..cedula = json['cedula'] as bool?
  ..quant = json['quant'] as int?
  ..valor =
      json['valor'] == null ? null : Decimal.fromJson(json['valor'].toString());

Map<String, dynamic> _$ApiPdvTrocoToJson(ApiPdvTroco instance) =>
    <String, dynamic>{
      'cedula': instance.cedula,
      'quant': instance.quant,
      'valor': instance.valor?.toDouble(),
    };

Is there a way to configure "json_serialize" to generate code like this?

kevmoo commented 2 months ago

You need to use a converter. See https://pub.dev/packages/json_serializable#custom-types-and-custom-encoding

alexrosabr commented 2 months ago

Thanks! For reference, here's my DecimalConverter:

class DecimalConverter implements JsonConverter<Decimal?, dynamic> {
  const DecimalConverter();

  @override
  Decimal? fromJson(dynamic json) => Decimal.tryParse('$json');

  @override
  double? toJson(Decimal? object) => object?.toDouble();
}

I had to use dynamic -- the API may return {"multiplier":0} sometimes.