flutter List<String> switchType = [] 转为fromJson
时间: 2024-02-24 12:55:38 浏览: 137
假设你要将以下JSON字符串转换为Dart对象:
```
{
"switchType": ["type1", "type2", "type3"]
}
```
你可以定义一个包含 `fromJson` 工厂方法的Dart类来实现转换。例如:
```dart
class Switches {
List<String> switchType;
Switches({this.switchType});
factory Switches.fromJson(Map<String, dynamic> json) {
return Switches(
switchType: List<String>.from(json['switchType']),
);
}
}
```
然后,你可以使用 `json.decode` 方法将JSON字符串转换为 `Map` 对象,再使用 `fromJson` 工厂方法将 `Map` 转换为 `Switches` 对象。例如:
```dart
String jsonString = '{"switchType":["type1","type2","type3"]}';
Map<String, dynamic> jsonMap = json.decode(jsonString);
Switches switches = Switches.fromJson(jsonMap);
print(switches.switchType); // ["type1", "type2", "type3"]
```
阅读全文