颤振:json_serializable 1 => 真,0 => 假

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

我正在使用 json_serializable 将 Map<dynamic, dynamic> 解析为我的对象。 示例:

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

  Todo(this.title, this.done);

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

因为我从 api 得到 'done': 1,我得到以下错误:

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

如何将 1 = true0 = false 转换为 json_serializable?

您可以使用自定义转换器(在此示例中,由于方法 _durationFromMilliseconds,它是 intDuration):

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

所以在您的代码中可能是这样的:

@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);
}