1

I receive json from api with string array. Then I set it to local variable with type List.

if (json['x'] is List) {
  List<String> x = json['x'];
  print(x);
}

When I run application, Chrome show me a warning: "Ignoring cast fail from JSArray to List"

What should I do with that?


  • Angular 5.0.0-alpha+6
  • Chrome 63.0.3239.132
  • Dart VM version: 2.0.0-dev.32.0
Cododoc
  • 125
  • 8
  • I assume this is from DDC, right? dar2js for Dart2 is work in progress. I guess it will be only relevant if the warning is shown there as well. See also https://github.com/dart-lang/sdk/blob/9ee735b659ea0097197ff857ca7debe579e483bd/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart#L428-L451 – Günter Zöchbauer Mar 07 '18 at 10:02

1 Answers1

1

JSON encodes all arrays as List<dynamic>, since that is the specification.

If you want to cast something to List<String>, you can't rely on just an implicit cast like you did in Dart 2. You must either use the real type:

List x = json['x'];

Or use the .cast function:

var x = (json['x'] as List).cast<String>();

I realize that is more writing than before. You might want to look at JSON serialization package such as json_serializable or built_value if you don't like the boiler-plate around this.

matanlurey
  • 8,096
  • 3
  • 38
  • 46