忽略从JSArray到List< String>的转换失败 [英] Ignoring cast fail from JSArray to List<String>
问题描述
我从api使用字符串数组接收json。然后将其设置为类型为List的局部变量。
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);
}
当我运行应用程序时,Chrome会向我显示警告:忽略强制转换失败JSArray列出
When I run application, Chrome show me a warning: "Ignoring cast fail from JSArray to List"
我该怎么办?
- Angular 5.0.0-alpha + 6
- Chrome 63.0.3239.132
- Dart VM版本:2.0.0 -dev.32.0
推荐答案
JSON将所有数组编码为 List<动态>
,因为这是规范。
JSON encodes all arrays as List<dynamic>
, since that is the specification.
如果您想将某些内容投射到 List< String>
,您不能像在Dart 2中那样仅依赖隐式转换。您必须使用实型:
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'];
或使用 .cast
函数:
var x = (json['x'] as List).cast<String>();
我意识到这比以前写的更多。如果您不喜欢样板,则可能需要查看JSON序列化程序包,例如 json_serializable
或 built_value
解决这个问题。
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.
这篇关于忽略从JSArray到List< String>的转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!