json - 颤振: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
解决方案
您可以拥有自定义转换器(在此示例中,这int
要Duration
归功于方法_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);
}
推荐阅读
- python - 从选择列表中获取对象的 ID。Django,表格
- android - 使用 XmlPullParser 为特定标签解析 XML?
- azure-application-insights - Kusto 查询渲染函数忽略指定的 Y 范围
- java - 聚合多个休息调用spring boot 2
- javascript - 内容编辑模式应该是 ContentCard 组件的一部分吗?
- c# - Unity - 将参数覆盖与正常分辨率混合
- javascript - 在 PHP 中使用 innerHTML 加载 TinyMCE
- linker - xv6 中的 ELF 标头是什么?
- dialogflow-es - 在对话流中获得多个意图匹配
- python - 用 K-Means 聚类并重塑为彩色图像