Skip to content

Allow nullable JsonConverter's to work with both nullable and non-nullable types #822

Closed
@shilangyu

Description

@shilangyu
  • Dart version: Dart SDK version: 2.12.0 (stable) (Thu Feb 25 19:50:53 2021 +0100) on "linux_x64"
  • json_serializable version: 4.0.2

When creating a custom JsonConverter that handles nullable types, it will not be applied to non-nullables. Example, consider this:

import 'package:json_annotation/json_annotation.dart';

part 'mydata.g.dart';

class ForceUtcDateTime implements JsonConverter<DateTime?, String?> {
  const ForceUtcDateTime();

  @override
  DateTime? fromJson(String? json) => json == null
      ? null
      : DateTime.parse('$json${json.endsWith('Z') ? '' : 'Z'}');

  @override
  String? toJson(DateTime? json) => json?.toIso8601String();
}

@JsonSerializable()
@ForceUtcDateTime()
class MyData {
  final DateTime created;
  final DateTime? updated;

  const MyData({required this.created, this.updated});

  factory MyData.fromJson(Map<String, dynamic> json) => _$MyDataFromJson(json);
  Map<String, dynamic> toJson() => _$MyDataToJson(this);
}

A custom DateTime converter is created that handles DateTime?. The generated code is as follows:

MyData _$MyDataFromJson(Map<String, dynamic> json) {
  return MyData(
    created: DateTime.parse(json['created'] as String),
    updated: const ForceUtcDateTime().fromJson(json['updated'] as String?),
  );
}

Map<String, dynamic> _$MyDataToJson(MyData instance) => <String, dynamic>{
      'created': instance.created.toIso8601String(),
      'updated': const ForceUtcDateTime().toJson(instance.updated),
    };

I would expect both created and updated to be handled by my ForceUtcDateTime converted, not just updated

If this is intended, I would like to know what is the expected way of handling such cases.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions