-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
dart:convert jsonEncode() throws an exception if the method toJson() is defined in an extension. #42742
Comments
Extensions are dependent on static types and does therefore not work on dynamic: If using the debugger we can see the next part of the stacktrace:
The _defaultToEncodable method is defined as: dynamic _defaultToEncodable(dynamic object) => object.toJson(); We can reproduce this problem fairly simple by: dynamic _defaultToEncodable(dynamic object) => object.toJson();
class A { }
extension JsonA on A {
void toJson() => print('Hey');
}
void main() {
print(_defaultToEncodable(A()));
} Which returns:
|
@julemand101 Thank you for taking the time to write such a detailed explanation. It might be useful for others who come across the same issue. The use of the data-type I'll close this issue now. |
Issued a pull request (#47875) to update the docs, because the docs are not clear on this issue. My use case was extending an enum: see https://stackoverflow.com/questions/70272959/jsonencode-doesnt-work-with-enum-extensions-is-there-a-workaround |
My SDK version is:
Dart VM version: 2.9.0-14.1.beta (beta) (Tue Jun 9 10:52:57 2020 +0200) on "linux_x64"
When attempting to move the method
toJson()
to an extension I noticed thatjsonEncode()
does not behave as expected.If the method
toJson()
is defined within the classA
(see below) the program produces the expected output:{"index":0}
However, if
toJson()
is defined within the extensionJsonA
dart:convert does not seem to have access totoJson
and a call tojsonEncode
results in this unhandled exception:The text was updated successfully, but these errors were encountered: