如何在扑中解析2D列表的json

时间:2019-10-23 12:02:17

标签: json parsing flutter dart

我想解析这个json

'supperset':[
  [1,2,3],
  [4,5,6],
  [1,8,9]
 ]

我从服务器获取数据进行解析时使用此代码

class Session {

final List<List<int>> supersets;
Session._({ this.supersets});
factory Session.fromJson(Map jsonMap) {

 return new Session._(

  supersets : (jsonMap['superSets'].cast<List<int>>()),

);
}
}

但是当此代码中的用户得到此错误时

type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast

如何解析它是正确的,但是什么导致此错误

2 个答案:

答案 0 :(得分:0)

问题1

type 'List<dynamic>' is not a subtype of type 'List<int>' in type cast

发生此错误是因为您要转换整数列表,但是 YOU 知道它是整数列表,而不是字符串列表。 Dart不知道json将要检索的列表类型。

因此,您必须期望一个List<dynamic>,这意味着该列表可以是任何变量。然后将其用作整数。

问题2

您输入了错误的类型。

supersets : (jsonMap['superSets'].cast<List<int>>()),

应该是

supersets : (jsonMap['supperset'].cast<List<int>>()),

最终脚本应为:

class Session {
  final List<List<dynamic>> supersets;
  Session._({this.supersets});
  factory Session.fromJson(Map jsonMap) {
    return new Session._(
      supersets: (jsonMap['supperset'].cast<List<dynamic>>()),
    );
  }
}

答案 1 :(得分:0)

List.from()在处理从JSON解码的具有相同成员类型的列表时很有用。

mapList.from合并,将您的List<dynamic>转换为List<List<int>>,这可能是您最终想要得到的。

void main() {
  var jsonMap = json.decode('{"superset":[[1,2,3],[4,5,6],[1,8,9]]}');

  // jsonMap['superset'] is a List<dynamic>, so lets 'map' it to a List<List<int>>
  // by mapping each of the top level elements to a List<int>
  // each 'l' is also a List<dynamic>, so convert that to a List<int> using .from
  var listOfLists =
      jsonMap['superset'].map<List<int>>((l) => List<int>.from(l)).toList();

  print(listOfLists); // expect [[1, 2, 3], [4, 5, 6], [1, 8, 9]]
  print(listOfLists.runtimeType); // expect List<List<int>>
}