flutter - 使用 Json 错误是 * type 'List' 不是 'String' 类型的子类型*
问题描述
这是我的回应 http://dummy.restapiexample.com/api/v1/employees
我正在显示来自 api 的列表,我在 response.body 中得到了响应,但随后不知道发生了什么
我的 PODO 或模型是
class NewData {
String id;
String employeeName;
String employeeSalary;
String employeeAge;
String profileImage;
NewData(
{this.id,
this.employeeName,
this.employeeSalary,
this.employeeAge,
this.profileImage});
factory NewData.fromJson(Map<String, dynamic> json) => NewData(
id: json["id"],
employeeName: json["employee_name"],
employeeSalary: json["employee_salary"],
employeeAge: json["employee_age"],
profileImage: json["profile_image"],
);
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['employee_name'] = this.employeeName;
data['employee_salary'] = this.employeeSalary;
data['employee_age'] = this.employeeAge;
data['profile_image'] = this.profileImage;
return data;
}
}
我的 Main.dart 是
body: Container(
child: Column(
children: <Widget>[
FutureBuilder<NewData>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text("ERROR : - " + snapshot.error.toString());
}
List<NewData> data = snapshot.data as List<NewData>;
return new ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return new ListTile(
title: new Text(data[index].employeeName),
);
},
);
} else {
// By default, show a loading spinner.
return Center(
child: CircularProgressIndicator(),
);
}
}),
],
),
),
);
}
Future<NewData> fetchPost() async {
var response = await http.get(url);
if (response.statusCode == 200) {
// If server returns an OK response, parse the JSON.
var resp = json.decode(response.body);
print(resp.toString());
return NewData.fromJson(resp);
} else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}
但我收到了这个错误
“列表”类型不是“字符串”类型的子类型
帮我解决这个问题,我如何摆脱它?
解决方案
您请求的 JSON 返回一个对象列表,并且在您的代码中,您正在解析单个对象。因此,当您解析它时,NewData.fromJson(resp)
您会尝试解析对象列表而不是单个对象。
你最好这样做:
Iterable l = json.decode(rseponse.body);
List<NewData> dataList = l.map((Map model)=> NewData.fromJson(model)).toList();
然后,您将能够将fetchPost()
返回类型更新为Future<List<NewData>>
.
推荐阅读
- mongodb - MongoDB Go 驱动程序在不应该查看本地主机时
- javascript - 未捕获的类型错误:无法使用 for 循环设置 null 的属性“innerHTML”
- python - 如何将 pandas 与 Robot 框架集成并运行查询
- javascript - 了解函数返回
- powershell - 使用 Build Agent Name 获取 Build Agent ID
- java - 当任务总数少于分配的线程数时的 ExecutorService 行为
- php - 每个连接的多维数组
- python - .append() 用于 python 中的两个列表。检查思维
- pandas - 熊猫可以解析带有未知数量评论,标题和要跳过的行的csv文件
- android - alignParent - 左/开始和右/结束