Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dart JSON String convert to List String

Tags:

flutter

dart

I have an API that calls the json String array as follows:

[
  "006.01.01",
  "006.01.01 1090",
  "006.01.01 1090 1090.950",
  "006.01.01 1090 1090.950 052",
  "006.01.01 1090 1090.950 052 A",
  "006.01.01 1090 1090.950 052 A 521219",
  "006.01.01 1090 1090.950 052 A 521219",
  "006.01.01 1090 1090.950 052 A 521219",
  "006.01.01 1090 1090.950 052 A 521219",
  "006.01.01 1090 1090.950 052 A 521219",
  "006.01.01 1090 1090.950 052 B",
  "006.01.01 1090 1090.950 052 B 521211",
  "006.01.01 1090 1090.950 052 B 521211",
  "006.01.01 1090 1090.994",
  "006.01.01 1090 1090.994 001",
  "006.01.01 1090 1090.994 001 A",
  "006.01.01 1090 1090.994 001 A 511111",
  "006.01.01 1090 1090.994 001 A 511111",
  "006.01.01 1090 1090.994 001 A 511111",
  "006.01.01 1090 1090.994 001 A 511111"
]

I intend to convert the json to the List in the dart. I tried the script below :

json.decode(response.body).cast<List<String>();

but it didn't work, how should the script be correct?

like image 657
Denis Ramdan Avatar asked Nov 19 '18 14:11

Denis Ramdan


People also ask

How do you change a String to a list in flutter?

In Flutter and Dart, you can turn a given string into a list (with string elements) by using the split() method. To convert a list of strings to a string, you can use the join() method.


1 Answers

The result of parsing a JSON list is a List<dynamic>. The return type of jsonDecode is just dynamic.

You can cast such a list to a List<String> as

List<String> stringList = (jsonDecode(input) as List<dynamic>).cast<String>();

You can also just use it as a List<dynamic> and then assign each value to String:

List<dynamic> rellyAStringList = jsonDecode(input);
for (String string in reallyAStringList) { ... }

The effect is approximately the same - each element is checked for being a string when it is taken out of the list.

like image 178
lrn Avatar answered Sep 29 '22 03:09

lrn