Json_serializable.dart: Generated code for DateTime with extension is incorrect.

Created on 5 Dec 2019  Â·  2Comments  Â·  Source: google/json_serializable.dart

Version:

Flutter 1.12.13+hotfix.2 • channel beta • https://github.com/flutter/flutter.git
Framework • revision 4f54e46f56 (10 hours ago) • 2019-12-04 09:20:18 -0800
Engine • revision 6955b06ced
Tools • Dart 2.7.0

json_annotation: ^3.0.0
json_serializable: ^3.2.0

I'm using this class:

@JsonSerializable()
class Test {
  final DateTime time;

  Test({
    @required this.time
  });

  factory Test.fromJson(Map<String, dynamic> json) => _$TestFromJson(json);
  Map<String, dynamic> toJson() => _$TestToJson(this);
}

Without an extension to DateTime it generates the correct DateTime decoding methods:

Test _$TestFromJson(Map<String, dynamic> json) {
  return Test(
    time: json['time'] == null ? null : DateTime.parse(json['time'] as String),
  );
}

Map<String, dynamic> _$TestToJson(Test instance) => <String, dynamic>{
      'time': instance.time?.toIso8601String(),
    };

But when I add any extension to DateTime:

extension ExtendedDateTime on DateTime {}

The output changes to the below, and decoding/encoding fails.

Test _$TestFromJson(Map<String, dynamic> json) {
  return Test(
    time: json['time'],
  );
}

Map<String, dynamic> _$TestToJson(Test instance) => <String, dynamic>{
      'time': instance.time,
    };

It also doesn't apply custom JsonConverters

bug

Most helpful comment

I just upgraded things. Try the latest version. I think this is fixed now w/ the latest pkg:analyzer

All 2 comments

That's WEIRD! Wondering if it's a bug in new analyzer APIs. Will investigate.

I just upgraded things. Try the latest version. I think this is fixed now w/ the latest pkg:analyzer

Was this page helpful?
0 / 5 - 0 ratings

Related issues

4BooM04 picture 4BooM04  Â·  3Comments

ollydixon picture ollydixon  Â·  6Comments

volskaya picture volskaya  Â·  4Comments

hatjs880328s picture hatjs880328s  Â·  3Comments

Nico04 picture Nico04  Â·  5Comments