【问题标题】:how to parse json of 2D list in flutter如何在颤动中解析二维列表的json
【发布时间】:2019-10-23 12:02:17
【问题描述】:

我想解析这个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

如何解析它是正确的,但是会出现这个错误

【问题讨论】:

    标签: json parsing flutter dart


    【解决方案1】:

    问题 1

    type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;int&gt;' in type cast

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

    因此你必须期待List&lt;dynamic&gt;,这意味着列表可以是任何变量。然后你把它当作整数使用。

    问题 2

    您输入错误。

    supersets : (jsonMap['superSets'].cast&lt;List&lt;int&gt;&gt;()),

    应该是

    supersets : (jsonMap['supperset'].cast&lt;List&lt;int&gt;&gt;()),

    最终的脚本应该是:

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

    【讨论】:

    • 您尚未解决如何将其转换为 List&lt;int&gt; 以防 OP 需要以这种方式键入,例如用于 API 调用 - 或者只是想在后面的行中使用强类型来辅助 IDE。
    【解决方案2】:

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

    mapList.from 结合起来,将您的List&lt;dynamic&gt; 转换为List&lt;List&lt;int&gt;&gt;,这可能是您最终想要的结果。

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

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 2021-02-01
      • 2019-11-08
      • 1970-01-01
      • 2019-08-31
      • 2020-01-14
      • 2020-10-28
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多