将字符串转换为2D列表Flutter

huangapple go评论53阅读模式
英文:

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&lt;String&gt; stringList = (jsonDecode(serviceWantList) as List&lt;dynamic&gt;).cast&lt;String&gt;();

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 =
      &#39;[[Service is the best, 300, 1], [Man is awesome, 4200, 1],[Service is the best, 300, 1], [Man is awesome, 4200, 1]]&#39;;

  input = input.replaceAllMapped(
      RegExp(r&#39;([a-zA-Z ]+)(?=,)&#39;), (match) =&gt; &#39;&quot;${match.group(0)}&quot;&#39;);
  List&lt;List&lt;dynamic&gt;&gt; output = List.from(jsonDecode(input))
      .map((e) =&gt; List.from(e).cast&lt;dynamic&gt;())
      .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 (").

huangapple
  • 本文由 发表于 2023年5月14日 18:24:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定