json - 如何在 Flutter 中发出 API 请求
问题描述
我是 Flutter 的新手,所以我不确定我应该如何进行 API 调用,来自我使用 Retrofit 的 Java。
JSON响应:
{
"total": 13,
"rows": [
{
"id": 1,
"name": "Name"
}
]
}
型号类:
class Category {
int total;
List<Rows> rows;
Category({this.total, this.rows});
Category.fromJson(Map<String, dynamic> json) {
total = json['total'];
if (json['rows'] != null) {
rows = new List<Rows>();
json['rows'].forEach((v) {
rows.add(new Rows.fromJson(v));
});
}
}
}
class Rows {
String name;
Rows({this.name});
Rows.fromJson(Map<String, dynamic> json) {
name = json['name'];
}
}
主班
List<Rows> rows = [];
Future<List<Rows>> getData() async {
var response = await http.get(
Uri.encodeFull("http://192.168.0.10/api/v1/categories"),
headers: {
"Authorization": "API",
"Accept": "application/json"
}
);
var jsonData = json.decode(response.body);
}
我不知道如何处理我尝试使用 Rows.fromJson() 获取对象,但我只得到'Instance of Rows'并且通过调用名称我得到空值。
解决方案
该方法是正确的,但对于列表,您应该使用 list.map 来反序列化列表。
试试这个,我没有测试它,我只是看着你的例子写的
var response = await http.get(
Uri.encodeFull("http://192.168.0.10/api/v1/categories"),
headers: {
"Authorization": "API",
"Accept": "application/json"
}
);
List<Rows> rows = [];
Map map = json.decode(response.body);
List l = map["rows"];
rows = l.map((map) => Rows.fromJson(map)).toList();
推荐阅读
- mysql - 哪个权限需要 mysql 用户才能将 EXECUTE 权限授予其他用户?
- python - PyCharm 更新,现在每个脚本都在 Python 控制台中执行
- python - flask.cli.NoAppException [flaskr 教程]
- pointers - Golang Struct 引用其他结构的指针或无指针以及为什么
- python - wxPython 仪表在 Linux 上冻结
- xml - XSLT 何时、复制和删除
- elasticsearch - Logstash 插件测试
- ios - 始终至少在屏幕底部显示一个单元格
- c# - 具有辅助角色的 Azure 服务总线主题和订阅
- python - 检查目标时出错:预期 dense_3 的形状为 (2,) 但得到的数组的形状为 (1,)