Home > Net >  Converting object to an encodable object failed in Flutter
Converting object to an encodable object failed in Flutter

Time:06-21

I have created a class like in the example here: https://docs.flutter.dev/development/data-and-backend/json

class NewUser {
String Username;
String Mail;
String Password;
Lang Language;

NewUser(this.Username, this.Mail, this.Password, this.Language);

NewUser.fromJson(Map<String, dynamic> json)
  : Username = json['Username'],
    Mail = json['Mail'],
    Password = json['Password'],
    Language = json['Language'];

Map<String, dynamic> toJson() => {
    'Username': Username,
    'Mail': Mail,
    'Password': Password,
    'Language': Language
};
}

When i try calling toJson it fails with: Converting object to an encodable object failed: Instance of 'NewUser'

NewUser user = NewUser('username', 'mail', 'password', Lang.cs);
String json = jsonEncode(user);
print(json);

Any idea how to fix this?

EDIT: It was becase "Language" is enum. How do I serialize enum?

CodePudding user response:

You can use Lang.name to encode to JSON and Lang.values.byName(...) to decode from JSON. Take a look below:


class NewUser {
  String Username;
  String Mail;
  String Password;
  Lang Language;

  NewUser(this.Username, this.Mail, this.Password, this.Language);

  NewUser.fromJson(Map<String, dynamic> json)
    : Username = json['Username'],
      Mail = json['Mail'],
      Password = json['Password'],
      Language = Lang.values.byName(json['Language']);

  Map<String, dynamic> toJson() => {
      'Username': Username,
      'Mail': Mail,
      'Password': Password,
      'Language': Language.name,
  };
}
  • Related