json_serializable.dart
json_serializable.dart copied to clipboard
Provide default value in JsonKey and use that instead of throwing type cast error
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.
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
I have same problem
when json['listSample']
return null, your code json['listSample'] as List<dynamic>
throw exception
You could always use a custom converter to accomplish this. Put the try/catch logic in the converter.
@Himanshuarora97, could you show us a sample code for achieving this?
@kevmoo , can we have a single converter covering all types or should we create one for each possible type?
If you have many target types you'll need many functions. One for each value
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.