【问题标题】:Flutter: json_serializable 1 => true, 0 => false颤振:json_serializable 1 => true,0 => false
【发布时间】:2021-07-10 14:47:12
【问题描述】:

我正在使用 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

如何使用 json_serializable 投射 1 = true0 = false

【问题讨论】:

    标签: json flutter dart serialization


    【解决方案1】:

    你可以有自定义转换器(在这个例子中它是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);
    }
    

    【讨论】:

    • 谢谢!你救了我!这就是我要找的东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2012-09-12
    • 2012-01-05
    相关资源
    最近更新 更多