颤振:json_serialized 1 => true,0 => false

st3*_*fb3 5 serialization json dart flutter

我正在使用 json_serialized 来解析Map<dynamic, dynamic>我的对象。例子:

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

  Todo(this.title, this.done);

  factory Todo.fromJson(Map<String, dynamic> json) => _$TodoFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

因为我是'done': 1从 api 获取的,所以出现以下错误:

Unhandled Exception: type 'int' is not a subtype of type 'bool' in type cast
Run Code Online (Sandbox Code Playgroud)

如何使用 json_serialized 强制转换1 = trueand 0 = false

小智 11

您可以拥有自定义转换器(在本示例中,这要int归功于Duration该方法_durationFromMilliseconds):

https://github.com/google/json_serialized.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);
}
Run Code Online (Sandbox Code Playgroud)