我试图加载数组 json(没有键的数组)并提取到对象列表中,这是我的示例代码:
我的 APICliet:
Future<List<OnBoardingModel>> fetchOnboarding() async {
try {
Response response = await dio.get("api/OnboardingItem");
return OnBoardingModel.fromJson(response.data) as List;
} catch (error, stacktrace) {
throw Exception("Exception occured: $error stackTrace: $stacktrace");
}
}
我的对象(使用quicktype生成):
List<OnBoardingModel> onBoardingModelFromJson(String str) => List<OnBoardingModel>.from(json.decode(str).map((x) => OnBoardingModel.fromJson(x)));
String onBoardingModelToJson(List<OnBoardingModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class OnBoardingModel {
OnBoardingModel({
this.id,
this.judul,
this.deskripsi,
this.urlGambar,
});
int id;
String judul;
String deskripsi;
String urlGambar;
factory OnBoardingModel.fromJson(Map<String, dynamic> json) => OnBoardingModel(
id: json["id"],
judul: json["judul"],
deskripsi: json["deskripsi"],
urlGambar: json["urlGambar"],
);
Map<String, dynamic> toJson() => {
"id": id,
"judul": judul,
"deskripsi": deskripsi,
"urlGambar": urlGambar,
};
}
最后我得到了一个错误显示:Exception: Exception occured: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' stackTrace: #0
,参考这一行return OnBoardingModel.fromJson(response.data) as List;
你能帮我解决这个案子吗?我谢谢你
更新
我的 json 格式:
[
{
"id": 0,
"judul": "string",
"deskripsi": "string",
"urlGambar": "string"
}
]