0

@JsonKey(name: "favourite") @Default("") String favourite

In my json favourite is rather Y and N , which mean true or false, possible to convert directly in freezed? So I can directly use boolean, instead of String

FeelRightz
  • 2,777
  • 2
  • 38
  • 73

1 Answers1

4

You can create a custom converter for the field.

class MyConverter implements JsonConverter<String, bool> {
  const MyConverter ();

  @override
  MyResponse fromJson(string input) {
    switch (input) {
      case "Y": return true;
      case "N": return false;
      default: throw NotSupportedError();
    }
  }

  @override
  String toJson(bool input) {
    switch (input) {
      case true: return "Y";
      case false: return "N";
      default: throw NotSupportedError();
    }
  }
}
@JsonKey(name: "favourite") @Default("") @MyConverter() String favourite
Abion47
  • 22,211
  • 4
  • 65
  • 88
  • still have to use String or can be `@JsonKey(name: "favourite") @Default(false) @MyConverter() boolean favourite` ? – FeelRightz Jul 04 '21 at 04:37
  • Hi, I followed your suggestion and I getting `'StringBoolConverter.fromJson' ('ProductItem Function(String)') isn't a valid override of 'JsonConverter.fromJson' ('String Function(bool)').` – FeelRightz Jul 04 '21 at 04:44
  • @FeelRightz What is `ProductItem`? You never mentioned that type in your question. – Abion47 Jul 04 '21 at 07:35