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>?
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>?
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);
You can turn it into the right type like this: