【问题标题】:How do I cast a multidimensional json array to a multidimensional dart list?如何将多维 json 数组转换为多维飞镖列表?
【发布时间】:2021-04-15 07:52:45
【问题描述】:

我得到一个 JSON 文件,其中包含一长串这样的数据。

[
  [
    [6.25575, 51.83439],
    [6.26408, 51.83342]
  ],
  [
    [6.25575, 51.83439],
    [6.26408, 51.83342]
  ]
]

当我写作时:

final List<List<List<double>>> data = await getJson('assets/data.json') as List<List<List<double>>>;

它给出了错误:_CastError (type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;List&lt;List&lt;double&gt;&gt;&gt;' in type cast)

getJson 函数:

Future<dynamic> getJson(String file) async {
  final String jsonData = await rootBundle.loadString(file);
  final dynamic data = await jsonDecode(jsonData);

  return data;
}

如何将此列表转换为List&lt;List&lt;List&lt;double&gt;&gt;&gt;

【问题讨论】:

    标签: arrays json list dart


    【解决方案1】:

    您需要单独投射不同的列表,如下所示:

    final List<List<List<double>>> data = (await getJson('assets/data.json') as List).map((e)=> (e as List).map((e) => (e as List).map((e) => e as double).toList()).toList()).toList();
    

    【讨论】:

    • 同一事物的替代语法:var data = [for (var l1 in getJson('assets/data.json)) [for (var l2 in l1) [ for (var v3 in l2) v3 as double]]];.
    【解决方案2】:

    我不知道这个解决方案是否比 Victor Eronmosele 提出的解决方案更具可读性,但由于我最终完成了它,所以我会发布它。但原理是一样的。只是创建这个新列表对象的另一种语法。

    import 'dart:convert';
    
    void main() {
      const input = '''
    [
      [
        [6.25575, 51.83439],
        [6.26408, 51.83342]
      ],
      [
        [6.25575, 51.83439],
        [6.26408, 51.83342]
      ]
    ]
    ''';
    
      final typedList = fromJson(jsonDecode(input) as List<dynamic>);
      print(typedList); // [[[6.25575, 51.83439], [6.26408, 51.83342]], [[6.25575, 51.83439], [6.26408, 51.83342]]]
      print(typedList.runtimeType); // List<List<List<double>>>
    }
    
    List<List<List<double>>> fromJson(List<dynamic> list1) => [
          for (final list2 in list1)
            [
              for (final list3 in list2)
                [for (final number in list3) number as double]
            ]
        ];
    
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2013-05-17
      • 2019-06-25
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 2015-08-18
      • 2014-05-13
      相关资源
      最近更新 更多