json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Provide default value in JsonKey and use that instead of throwing type cast error

Open rbresjer opened this issue 2 years ago • 4 comments

If for some reason an API returns another type than expected, you get an (e.g.) type '_GrowableList<dynamic>' is not a subtype of type 'Map<String, dynamic>?' in type cast error. I know you can use checked: true to get an exception instead of an error, but I'd like to use a default fallback value and fail silently. Is this easily achievable?

E.g. @JsonSerializable(useDefaultIfError: true) and @JsonKey(useDefaultIfError: true) which falls back to the defaultValue or null if the value cannot be initialised from the JSON.

rbresjer avatar Apr 25 '22 08:04 rbresjer

I had faced the similar kind of problem #899, I tweaked the library to handled my case. I'll try to build this type of config, maybe it will help other people also

hm-arora avatar Jul 23 '22 18:07 hm-arora

I have same problem when json['listSample'] return null, your code json['listSample'] as List<dynamic> throw exception

tvqphong001 avatar Aug 10 '22 07:08 tvqphong001

You could always use a custom converter to accomplish this. Put the try/catch logic in the converter.

kevmoo avatar Aug 10 '22 13:08 kevmoo

@Himanshuarora97, could you show us a sample code for achieving this?

deniskrr avatar Aug 26 '22 18:08 deniskrr

@kevmoo , can we have a single converter covering all types or should we create one for each possible type?

deniskrr avatar Oct 10 '22 13:10 deniskrr

If you have many target types you'll need many functions. One for each value

kevmoo avatar Oct 10 '22 16:10 kevmoo

I see... I thought we could do some generics magic as I'm really just looking for try { parse } catch { return default }—so the type is irrelevant.

deniskrr avatar Oct 11 '22 06:10 deniskrr