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

`JsonKey.fromJson` seems to be ignored #1409

Open busslina opened 3 months ago

busslina commented 3 months ago

My code:

@JsonSerializable()
class Person {
  @JsonKey(
    fromJson: unixTimeToDateTime,
    toJson: dateTimeToUnixTime,
    includeFromJson: true,
    includeToJson: true,
  )
  DateTime dateOfBirth;

  Person({required this.dateOfBirth});
}

DateTime unixTimeToDateTime(int secondsSinceEpoch) =>
    DateTime.fromMillisecondsSinceEpoch(
      secondsSinceEpoch * 1000,
      isUtc: true,
    );

int dateTimeToUnixTime(DateTime dateTime) =>
    dateTime.millisecondsSinceEpoch ~/ 1000;

Generated:

Person _$PersonFromJson(Map<String, dynamic> json) => Person(
      dateOfBirth: DateTime.parse(json['dateOfBirth'] as String),
    );

Any solution?

UPDATE: JsonConverter is not a solution because in many cases I need to specify the JsonKey.name too.

busslina commented 3 months ago

Seems that putting the top level fromJson function in the same file resolve it. So now it works, but why? I'm not using lib prefixes.

imagen

Demo video: https://mega.nz/file/FHZ1hAaA#rzsGJsyePyDpDr-okfCF9QRQ_GCIF1zSWvW2bPtPK90