简体   繁体   中英

Converting object to an encodable object failed in Flutter

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?

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,
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM