dart JSON String convert to List String

后端 未结 3 463
南方客
南方客 2021-01-04 10:14

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.95         


        
相关标签:
3条回答
  • 2021-01-04 10:25

    Try this one. Hope it helps.

    import 'dart:convert';
    
    void main() {
      String jsonResponse = '''
        ["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"]
      ''';
    
      dynamic jsonParsed = json.decode(jsonResponse);
    
    //   print(jsonParsed);
    
      print(jsonParsed[5]);
    }
    
    0 讨论(0)
  • 2021-01-04 10:30

    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.

    0 讨论(0)
  • 2021-01-04 10:33

    We can easily parse the JSON into a Dart array without the need of creating any class.

    main() {
      String arrayText = '{"tags": ["dart", "flutter", "json"]}';
    
      var tagsJson = jsonDecode(arrayText)['tags'];
      List<String> tags = tagsJson != null ? List.from(tagsJson) : null;
    
      print(tags);
    }
    

    Now you can see the result of printing the Dart Array.

    [dart, flutter, json]
    
    0 讨论(0)
提交回复
热议问题