Flutter: json_serializable 1 => true, 0 => false

Viewed 964

I'm using json_serializable for parsing Map<dynamic, dynamic> to my object. Example:

@JsonSerializable()
class Todo {
  String title;
  bool done;

  Todo(this.title, this.done);

  factory Todo.fromJson(Map<String, dynamic> json) => _$TodoFromJson(json);
}

Because I'm getting 'done': 1 from the api, I get following error:

Unhandled Exception: type 'int' is not a subtype of type 'bool' in type cast

How can I cast 1 = true and 0 = false with json_serializable?

1 Answers

You can have custom converter (in this example it's int to Duration thanks to the method _durationFromMilliseconds) :

https://github.com/google/json_serializable.dart/blob/master/example/lib/example.dart

So in your code it might be something like this :

@JsonSerializable()
class Todo {
  String title;

  @JsonKey(fromJson: _boolFromInt, toJson: _boolToInt)
  bool done;

  static bool _boolFromInt(int done) => done == 1;

  static int _boolToInt(bool done) => done ? 1 : 0;

  Todo(this.title, this.done);

  factory Todo.fromJson(Map<String, dynamic> json) => _$TodoFromJson(json);
}
Related