4

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?

0

1 Answer 1

2

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,
  };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.