0

I got a JSON file with a long list of data like this.

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

When I write:

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

It gives the error: _CastError (type 'List<dynamic>' is not a subtype of type 'List<List<List<double>>>' in type cast).

getJson function:

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

  return data;
}

How can a cast this list of lists to a List<List<List<double>>>?

2 Answers 2

2

You need to cast the different Lists individually like below:

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Alternative syntax for the same thing: var data = [for (var l1 in getJson('assets/data.json)) [for (var l2 in l1) [ for (var v3 in l2) v3 as double]]];.
1

I don't know if this solution is more readable than the one Victor Eronmosele did come up with but since I ended up making it I will just post it. But the principle is the same. Just another syntax for creating this new list object.

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]
        ]
    ];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.