Open RohanSenguptaMantisPro opened 2 months ago
Not sure I understand the issue.
Do you want any field to be null if the deserialization of it throws?
yes. If an empty string is received it should be converted to null when deserializing directly, rather than throwing conversion error ( trying to convert an empty string to Datetime, int etc ) and if we want any customization we can use hooks according to our wants.
The current (and intended) behavior is:
The raw value must be in a format that is valid for deserialization, else an exception is throw.
As a default behavior I don't want to change this (I think for 99% of users this is the correct approach). It would also be breaking. But I'm open for an opt-in solution, like a custom hook or an annotation property.
Then I would say this CustomHook works pretty well.
class NullableHook extends MappingHook {
const NullableHook();
@override
Object? beforeDecode(Object? value) {
return (value is String && value.isEmpty) ? null : value;
}
}
Only thing that has to be kept in mind is to add this hook to the fields wherever the empty string to null conversion functionality is desired.
We need this behavior as well. If the field is nullable, when deserialization isn't valid it should return null. And of course if it's declared non-nullable then it should throw an exception.
A global flag, or maybe better a global custom hook would be nice
In a class like this if
hook
was not used, and json response returnsemailVerified
as an empty string, dart_mappable gives conversion error.So to solve this we have to use
hook
But then for all the non-String fields we would have to use the hook with
@MappableField(hook: NullableHook())
. we have to repeat that for all the properties.Rather, it would have been better if it was done the way
.tryParse()
handles the conversion :If error in conversion then it will return null , if variable is nullable.
My Suggestion:
.tryParse()
so that Custom Hooks isn't required for this empty string conversion case at least,EmptyToNullHook
produce errors while trying to achieve the same that I did with theNullableHook
due to some reason ( also mentioned in the issue : #217 ) .