Flutter / dart json 编码和解码不转换动态类型

问题描述 投票:0回答:1
_CastError (type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast)

我在尝试将 json 字符串解码回创建它的对象列表时收到此错误。我不明白为什么它很难施放这个;底层动态类型显然是一个整数。这是下面的代码,经过编辑以更简洁地与问题相关。

class Obj extends Equatable {
  final List<int> scheduledTimes;
  final bool active;
...
Obj.fromJson(Map<String, dynamic> json)
      : scheduledTimes = json['scheduledTimes'] as List<int>,
        active = json['active'] as bool;

  Map<String, dynamic> toJson() {
    Map<String, dynamic> map = {};
    map['scheduledTimes'] = scheduledTimes;
    map['active'] = active;
    return map;
  }
...

我使用

json.encode
(它触发了 toJson())对此进行了编码,然后立即尝试
json.decode
这个但失败并出现错误:

_CastError (type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast)
json flutter dart codec
1个回答
0
投票

尝试使用

List.from

Obj.fromJson(Map<String, dynamic> json)
      : scheduledTimes = List.from(json['scheduledTimes'] ) ,
        active = json['active'] as bool;
© www.soinside.com 2019 - 2024. All rights reserved.