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

726

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);
}
Share:
726
st3ffb3
Author by

st3ffb3

Updated on December 29, 2022

Comments

  • st3ffb3
    st3ffb3 over 1 year

    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?

  • st3ffb3
    st3ffb3 about 3 years
    Thanks! You saved me! That's what I was looking for!