gpt4 book ai didi

json - Dart 的解析问题 - [无构建值 ^ 可序列化 ^ ]

转载 作者:IT王子 更新时间:2023-10-29 07:20:51 27 4
gpt4 key购买 nike

好人好样的,

[编辑:

在 dartpad 中运行

import 'dart:convert';
void main() {
const String _json = '{"myListInt": [1]}';
final Map<String, dynamic> _map = jsonDecode(_json);
final List<int> _list = _map['myListInt'] as List<int>;
_list.forEach((i) {
String _s = i.toString();
print(_s);
});
}

返回

Uncaught exception:
CastError: Instance of 'JSArray': type 'JSArray' is not a subtype of type
'List<int>'

如果我使用

  final List<int> _list = List<int>.from(_map['myListInt'] as List<int>);

List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int);

返回

Uncaught exception:
Cannot read property 'length' of undefined

]我做错了什么?

提前谢谢你

弗朗切斯科

最佳答案

代替这一行

myListInt: List<int>.from(_map['myListInt'] as List<int>),

你可以使用

myListInt: List<int>.generate(_map['myListInt'].length, (i)=>_map['myListInt'][i] as int 

基本上不是转换整个列表,而是必须一个接一个地转换每个元素。

关于json - Dart 的解析问题 - [无构建值 ^ 可序列化 ^ ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55709098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com