flutterdartbuilt-value

How to deserialize Date ISO String to DateTime Object in built_value serialization in dart?


I wanna serialize a json object including an ISOString date to a dart object using built value.

this is a sample json:

{
  "title": "test",
  "description": "test description",
  "date": "2020-06-05T11:42:38.585Z",
  "creator": {
    "email": "test@test.com"
  }
}

this is the model:

abstract class Post implements Built<Post, PostBuilder> {
  @nullable
  @BuiltValueField(wireName: '_id')
  String get id;

  String get title;

  String get description;

  DateTime get date;

  @nullable
  User get creator;

  Post._();

  static Serializer<Post> get serializer => _$postSerializer;

  factory Post([updates(PostBuilder b)]) = _$Post;

  factory Post.fromJson(Map<String, dynamic> map) =>
      serializers.deserializeWith(Post.serializer, map);

  Map<String, dynamic> toJson() =>
      serializers.serializeWith(Post.serializer, this);
}

and this is the error:

Deserializing '[title, test1, description, test1 description, date, 2020-06-05T...' to  
'Post' failed due to: Deserializing '2020-06-05T11:42:38.585Z' to 'DateTime' failed due  
to: type 'String' is not a subtype of type 'int' in type cast

how do I fix that?


Solution

  • You need to add a custom DateTime serializer that you can find here: Iso8601DateTimeSerializer

    1. create a new dart file (I named it iso8601_date_time_serializer.dart)
    2. paste the code from 1
    3. add the import to your serializers.dart file (import 'iso8601_date_time_serializer.dart';)
    4. edit your serializers.g.dart file
    Serializers _$serializers = (new Serializers().toBuilder()
    
      ..add(Iso8601DateTimeSerializer())
    
      ..add(Post.serializer) // I assume you have this in yours
    
      ..addPlugin(StandardJsonPlugin()))
    
    .build();
    

    Please note that this modification might be deleted if you regenerate the code with build_runner.

    In case you want to dig deeper, I got the answer from built_value GitHub issue 454