skip to Main Content

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

Answers


  1. 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();
       }
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search