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

JsonKey.fromJson seems to be ignored #1409

Open
busslina opened this issue Mar 28, 2024 · 1 comment
Open

JsonKey.fromJson seems to be ignored #1409

busslina opened this issue Mar 28, 2024 · 1 comment

Comments

@busslina
Copy link

busslina commented Mar 28, 2024

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
Copy link
Author

busslina commented Mar 28, 2024

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

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

No branches or pull requests

1 participant