Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting object to an encodable object failed

You don't need to add any libraries. You just have to implement fromJson and toJson functions in your object.

Example:

class LinkItem {
  final String name;
  final String url;

  LinkItem({this.name, this.url});

  LinkItem.fromJson(Map<String, dynamic> json)
      : name = json['n'],
        url = json['u'];

  Map<String, dynamic> toJson() {
    return {
      'n': name,
      'u': url,
    };
  }
}

Then you can call jsonEncode:

List<LinkItem> list = await getUserLinks();
list.add(linkItem);    
String json = jsonEncode(list);

Result:

  [{"n":"Google","u":"https://www.google.com/"},{"n":"Test","u":"https://www.test.com/"},{"n":"etc","u":"etc"}]

You can't just convert any arbitrary class instance to JSON.

One option is to provide a custom function to the JsonEncoder() constructor (via the toEncodable argument). This custom function should map your custom objects to types that JsonEncoder already knows how to handle (i.e. numbers, strings, booleans, null, lists and maps with string keys).

https://api.dartlang.org/stable/1.24.3/dart-convert/JsonEncoder-class.html

https://pub.dartlang.org/packages/json_serializable is a package that generates code for that so that you don't need to write it manually.

See also https://flutter.io/json/


In my case, I was attempting to use an integer key in a map object. Once I converted it to String, the error was resolved. Good luck.


In my case, I was attempting to add a DateTime directly to the map object. Once I converted it to String, the error was resolved.

Before

return {
  'birthDay', instance.birthDay
};

Now

return {
   'birthDay', instance.birthDay?.toIso8601String(),
};

I was trying to use an Uri into the map of dio request parameter. Converting it to String resolved the issue.

Error in directly using redirectUrl an instance of Uri

data: {
      'client_id': identifier,
      'client_secret': secret,
      'code': code,
      'redirect_uri': redirectUrl
    });

No error after converting to String.

data: {
      'client_id': identifier,
      'client_secret': secret,
      'code': code,
      'redirect_uri': redirectUrl.toString()
    });