Dart flutter: jsonDecode() parse a list of string to List<dynamic>

57 Views Asked by At

Dart flutter: jsonDecode() parse a list of string to List<dynamic>. e.g.

{
    name: 'John',
    hobbies: ['run', 'swim']
}

The hobbies is parsed to be a List<dynamic> with 2 items (of type String). should it be a List<String>?

2

There are 2 best solutions below

0
Ivo On BEST ANSWER

You can turn it into the right type like this:

   String jsonString = '["run","swim"]';
   var decoded = jsonDecode(jsonString);

   print(decoded.runtimeType); //prints List<dynamic>

   // Since decoded is a List<dynamic> the following line will throw an error, so don't do this
   //List<String> list = decoded;

   //this is how you can convert it, but will crash if there happens to be non-String in the list or if it isn't even a List
   List<String> list = List<String>.from(decoded);
  
   //if you are not sure if there are only Strings in the list or if it's even a List you could do this instead
   if (decoded is List) {
     List<String> list2 = decoded.whereType<String>().toList();
   }
0
timdrxe On

You can create a class like this:

class Human {
    String name;
    List<String> hobbies;

    Human({required this.name, required this.hobbies});

    factory Human.fromJson(Map<String, dynamic> json) {
        var human = Human(
            name: json['name'] as String,
            hobbies: List<String>.from(json['hobbies']),
        );
        return human;
    }
}

Now you can map the json to this class:

String jsonString = '{"name": "John", "hobbies": ["run", "swim"]}';
var data = jsonDecode(jsonString);
Human human = Human.fromJson(data);

// this returns "List<String>" now
print(human.hobbies.runtimeType);