Skip to content

dart:convert jsonEncode() throws an exception if the method toJson() is defined in an extension.  #42742

Closed
@simphotonics

Description

@simphotonics

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 that jsonEncode() does not behave as expected.
If the method toJson() is defined within the class A (see below) the program produces the expected output:

{"index":0}

However, if toJson() is defined within the extension JsonA dart:convert does not seem to have access to toJson and a call to jsonEncode results in this unhandled exception:

Unhandled exception:
Converting object to an encodable object failed: Instance of 'A'
#0      _JsonStringifier.writeObject (dart:convert/json.dart:687:7)
#1      _JsonStringStringifier.printOn (dart:convert/json.dart:876:17)
#2      _JsonStringStringifier.stringify (dart:convert/json.dart:861:5)
#3      JsonEncoder.convert (dart:convert/json.dart:261:30)
#4      JsonCodec.encode (dart:convert/json.dart:171:45)
#5      jsonEncode (dart:convert/json.dart:81:10)
#6      main (file:///home/dan/WORK/RemoteFlutterProjects/generic_enum/generic_enum/example/bin/example.dart:20:9)
#7      _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
#8      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
import 'dart:convert';

class A {
  const A(this.a);
  final int a;
  static const values = [A(1), A(2)];

  // Map<String, dynamic> toJson() => {
  //       'index': A.values.indexOf(this),
  //     };
}

extension JsonA on A {
  Map<String, dynamic> toJson() => {
        'index': A.values.indexOf(this),
      };
}

main() {
  print(jsonEncode(A.values[0]));
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions