Dart flutter:jsonDecode()解析一个字符串列表到List< dynamic>

ax6ht2ek  于 5个月前  发布在  Flutter
关注(0)|答案(2)|浏览(90)

Dart flutter:jsonDecode()解析一个字符串列表为List<dynamic>。例如:

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

字符串
hobbies被解析为一个List<dynamic>,有2个项目(类型为String)。它应该是一个List<String>吗?

i5desfxk

i5desfxk1#

你可以像这样把它变成正确的类型:

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();
   }

字符串

xsuvu9jc

xsuvu9jc2#

你可以像这样创建一个类:

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);

相关问题