Skip to content

jsonEncode with async toEncodable Function Causes Exception #59911

@yesilcimenahmet

Description

@yesilcimenahmet

When using jsonEncode with an async toEncodable function, it throws an exception, even when valid data is returned. Removing the async keyword resolves the issue, indicating that jsonEncode does not properly handle asynchronous operations in toEncodable.

import 'dart:convert';

enum MyEnum { a, b, c }

Map<String, dynamic> someValues() {
  return {'name': 'name value', 'age': 99, 'enum': MyEnum.a};
}

void jsonEncodeTest() {
  final object = someValues();
  final json = jsonEncode(
    object,
    toEncodable: (nonEncodable) async {
      if (nonEncodable is MyEnum) {
        return nonEncodable.toString();
      }
      return nonEncodable;
    },
  );
  print(json);
}

void main() {
  jsonEncodeTest();
}

The async keyword in toEncodable should allow asynchronous operations, and await should work without causing an exception.

The following exception is thrown:

Exception: Converting object did not return an encodable object: Instance of 'MyEnum'
UnsupportedObject: MyEnum.a
partialResult: {"name":"name value","age":99,"enum":

Therefore, this issue also occurs in Flutter. This is a critical problem and needs to be resolved quickly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-core-librarySDK core library issues (core, async, ...); use area-vm or area-web for platform specific libraries.closed-as-intendedClosed as the reported issue is expected behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions