首页 > 解决方案 > 颤振: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);
}

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

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

如何使用 json_serializable进行投射1 = true和转换?0 = false

标签: jsonflutterdartserialization

解决方案


您可以拥有自定义转换器(在此示例中,这intDuration归功于方法_durationFromMilliseconds):

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

推荐阅读