英文:
how convert string into 2d list flutter
问题
List<List<dynamic>> resultList = (jsonDecode(serviceWantList) as List<dynamic>).cast<List<dynamic>>();
英文:
I want to convert string into 2d array in Dart flutter
[[Service, 300, 1], [Service, 4200, 1]]
This is string I want to convert into a List so I can use the following with ListView in Flutter.
List<String> stringList = (jsonDecode(serviceWantList) as List<dynamic>).cast<String>();
I have tried this but I'm not getting the result I want.
I want to access list like this
[[Service, 300, 1], [Service, 4200, 1]]
I want to convert this in 2 list
so I access like index[0][0]
, index[0][1]
and so on.
答案1
得分: 1
jsonDecode 无法工作,因为字符串不是有效的 JSON。尝试执行以下操作:
String input =
'[[Service is the best, 300, 1], [Man is awesome, 4200, 1],[Service is the best, 300, 1], [Man is awesome, 4200, 1]]';
input = input.replaceAllMapped(
RegExp(r'([a-zA-Z ]+)(?=,)'), (match) => '"${match.group(0)}"');
List<List<dynamic>> output = List.from(jsonDecode(input))
.map((e) => List.from(e).cast<dynamic>())
.toList();
print(output[0][0].runtimeType);
print(output[0][1].runtimeType);
print(output[1][0].runtimeType);
print(output[1][1].runtimeType);
问题在于字符串包含未加引号的文本,在 JSON 中不允许这样的文本,因此我们需要用双引号(")括起字符串中的所有非数字值。
英文:
jsonDecode would not work because the string is not a valid JSON. Try doing the below:
String input =
'[[Service is the best, 300, 1], [Man is awesome, 4200, 1],[Service is the best, 300, 1], [Man is awesome, 4200, 1]]';
input = input.replaceAllMapped(
RegExp(r'([a-zA-Z ]+)(?=,)'), (match) => '"${match.group(0)}"');
List<List<dynamic>> output = List.from(jsonDecode(input))
.map((e) => List.from(e).cast<dynamic>())
.toList();
print(output[0][0].runtimeType);
print(output[0][1].runtimeType);
print(output[1][0].runtimeType);
print(output[1][1].runtimeType);
The problem is that the string contains unquoted text, which is not allowed in JSON; hence we need to enclose all the non-numeric values in the string in double quotes (").
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论