Home > Back-end >  Freezed & json_serializable handling parsing error
Freezed & json_serializable handling parsing error

Time:08-27

I'm looking for a general solution for handling parsing errors of complex (nested fields of Any type) objects using Freezed and json_serializable.
It should use the default value in case a field can't be parsed, and not compromise the whole object.

Let's take this class for example:

@freezed
class Interest with _$Interest {
  const factory Interest({
    @Default('') String id,
    required String slug,
    required String name,
    required String image,
    required bool isPublic,
  }) = _Interest;

  factory Interest.fromJson(Map<String, dynamic> json) =>
      _$InterestFromJson(json);
}

For illustration purposes, the backend response that I'm parsing could either have the id as String (as I have defined it) or int.
In the latter case, I will get a parsing error (as my id is a String and I received an int).

As a consequence, the whole object can't be parsed, even though the rest of the data is fine.

Thanks! ✌️

CodePudding user response:

You can create your own implementation of JsonConverter and annotate the specific field with it. Then you can control how you handle the conversion yourself, check typing and set to default values as you please.

Check details here:

https://pub.dev/packages/json_serializable#custom-types-and-custom-encoding

And here:

https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html

CodePudding user response:

You can set id property as dynamic

  • Related