arrays - 解析复杂的 JSON Flutter
问题描述
我正在尝试将这些复杂的 JSON 数据解析为 Flutter 应用程序。我能够成功获取 JSON 数据,但无法在应用程序中显示数据。请参阅下面的代码和 JSON 数据。我做错了什么?
{
"response": {
"cars": [
[
{
"id": 1,
"name": "Ford Mustang GT",
"class": "Muscle Car"
},
{
"id": 2,
"name": "Dodge Challenger",
"class": "Muscle Car"
},
{
"id": 3,
"name": "Chevrolet Camaro",
"class": "Muscle Car"
},
{
"id": 4,
"name": "Pontiac Firebird",
"class": "Muscle Car"
}
]
]
}
}
class Cars {
Cars({
this.id,
this.name,
this.carClass,
});
int id;
String name;
String carClass;
factory Cars.fromJson(Map<String, dynamic> json) => Cars(
id: json["id"],
name: json["name"],
carClass: json["class"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"class": carClass,
};
}
class ApiService {
Future<List<Cars>> getCars() async {
http.Response response = await http.get('http://localhost:3000/response');
var body;
if (response.statusCode == 200) {
body = jsonDecode(response.body);
List<dynamic> carList = body['response'];
print(body);
List<Cars> res =
carList.map((dynamic item) => Cars.fromJson(item)).toList();
return res;
}
}
}
解决方案
您可以使用此应用程序帮助构建类。( https://app.quicktype.io/ )
这些是您必须为获得的对象使用的类。请务必更改您认为相关的类的名称。
class Response {
Response({
this.response,
});
final ResponseClass response;
factory Response.fromJson(Map<String, dynamic> json) => Response(
response: ResponseClass.fromJson(json["response"]),
);
Map<String, dynamic> toJson() => {
"response": response.toJson(),
};
}
class ResponseClass {
ResponseClass({
this.cars,
});
final List<List<Car>> cars;
factory ResponseClass.fromJson(Map<String, dynamic> json) => ResponseClass(
cars: List<List<Car>>.from(json["cars"].map((x) => List<Car>.from(x.map((x) => Car.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"cars": List<dynamic>.from(cars.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class Car {
Car({
this.id,
this.name,
this.carClass,
});
final int id;
final String name;
final String carClass;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
carClass: json["class"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"class": carClass,
};
}
最后,替换这一行:
body = jsonDecode(response.body);
List<dynamic> carList = body['response'];
print(body);
List<Cars> res =
carList.map((dynamic item) => Cars.fromJson(item)).toList();
有了这个:
return Response.fromJson(response.body);
并替换函数返回给 Response 的数据类型。
推荐阅读
- python - rasa_nlu.model.UnsupportedModelError:模型版本太旧,无法由此 Rasa NLU 实例加载
- javascript - Laravel-Vue.js 错误 - Uncaught SyntaxError: Unexpected token '<'
- javascript - 是否可以通过 JavaScript Web 应用程序从笔记本电脑获取服务标签?
- python - python:while True vs while(条件)效率
- javascript - Mapbox GL JS以编程方式更改标记图像?
- sql - 如何使用 SQL 在 CosmosDB 中搜索数组
- laravel - 如果没有任何前端框架,Laravel Mix.extract 是否仍然有用?
- laravel - 使用 owen-it/laravel-auditing 包有没有办法将值从 user_id 更改为 user_name?
- ios - UITableView 排序 - 我做错了什么?
- django - 已经在 Django 中填充表单数据后如何更改表单数据