3

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! ✌️

deniskrr
  • 952
  • 1
  • 6
  • 12

3 Answers3

1

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

Robert Sandberg
  • 6,832
  • 2
  • 12
  • 30
  • Looks promising! The only issue is that I'm looking for something general... With this approach, I think I would have to write code for each possible type + annotate every single field. – deniskrr Aug 29 '22 at 08:26
0

You can do this with the checked boolean property in @JsonSerializable() annotation. You should be aware that a CheckedFromJsonException will be thrown during deserialization if parsing fails.

https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/checked.html

The problem with this is that it does not tell you which property is responsible for the cast parse error. You would get something like:

type 'double' is not a subtype of type 'int' in type cast

You may have to result in handling this manually, without the help of json_serializable.

davidn
  • 378
  • 4
  • 12
-2

You can set id property as dynamic

Tomislav Juroš
  • 266
  • 2
  • 7
  • This implies that I lose the type information of this field. Not really what I'm looking for here—but thanks. – deniskrr Aug 26 '22 at 14:54