我试图加载数组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"
}
]
答案 0 :(得分:4)
最后我得到了答案,只需使用以下内容替换返回值:
return (response.data as List)
.map((x) => OnBoardingModel.fromJson(x))
.toList();
完整代码:
Future<List<OnBoardingModel>> fetchOnboarding() async {
try {
Response response = await dio.get("api/OnboardingItem");
// if there is a key before array, use this : return (response.data['data'] as List).map((child)=> Children.fromJson(child)).toList();
return (response.data as List)
.map((x) => OnBoardingModel.fromJson(x))
.toList();
} catch (error, stacktrace) {
throw Exception("Exception occured: $error stackTrace: $stacktrace");
}
}
希望这个答案可以帮助其他刚起步的客人。
答案 1 :(得分:1)
导入'dart:convert';
if request.method == 'POST':
if request.files:
pdf = request.files["pdf"]
print(pdf)
return redirect()
return '''<form action="/Admin/upload-image" method='POST'>
<div class="form-group">
<label>Select PDF</label>
<div class="custom-file">
<input type="file" class="custom-file-input" name="pdf" id="pdf">
<label class="custom-file-label" for="image">Select PDF</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
</form>'''
最终欢迎= WelcomeFromJson(jsonString);