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();
}
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;
}
}
字符串 现在你可以将jsonMap到这个类:
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);
2条答案
按热度按时间i5desfxk1#
你可以像这样把它变成正确的类型:
字符串
xsuvu9jc2#
你可以像这样创建一个类:
字符串
现在你可以将jsonMap到这个类:
型