【发布时间】:2021-12-29 07:34:57
【问题描述】:
我可以解码来自服务器的响应,但我不知道这是什么错误:\
这是我在 showproduct 类中的请求代码:
if (response.statusCode == 200) {
setState(() {
var bodybytedecoded= jsonDecode(utf8.decode(response.bodyBytes));
final product= ProductModel.fromJson(bodybytedecoded); // console shows error come from this line
print(product);
}
});
}
else {
print(response.reasonPhrase);
}
在我的模型类中,我有:
class ProductModel{
final int id;
final String name;
final String regular_price;
final String description;
final List<ImageModel> image;
ProductModel({ required this.id,required this.name,required this.regular_price, required this.description,required this.image});
factory ProductModel.fromJson(Map<String,dynamic> json){
final name = json["name"];
final id = json ["id"];
final regular_price = json["regular_price"];
final description = json["description"];
final image = json["image"];
return ProductModel(id: id, name: name, regular_price: regular_price, description: description, image: image);
}
Map<String,dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data["id"] = this.id;
data["name"] = this.name;
data["regular_rice"] = this.regular_price;
data["description"] = this.description;
data["image"] = this.image;
return data;
}
}
class ImageModel{
final String src;
ImageModel({required this.src});
factory ImageModel.fromJson(Map<String,dynamic> json ){
return ImageModel(src: json["src"]);
}
}
我不知道这个错误是为了什么,我的模型类有什么问题吗?还是我的要求? 如果有人能告诉我一个真正的方法,我将不胜感激。
这是完整的错误:
E/flutter (31338): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'
E/flutter (31338): #0 _ShowProductState.FetchItems.<anonymous closure> (package:mystore/ProductPages/showproduct.dart:219:46)
E/flutter (31338): #1 State.setState (package:flutter/src/widgets/framework.dart:1088:30)
E/flutter (31338): #2 _ShowProductState.FetchItems (package:mystore/ProductPages/showproduct.dart:215:7)
E/flutter (31338): <asynchronous suspension>
E/flutter (31338):
这是来自服务器的 json 正文:
[
{
"id": 56012,
"name": "a name",
"slug": "a slug",
"description": "<p>آب آشامیدنی پیورلایف 1/5 لیتری نستله</p>\n",
"regular_price": "45000",
"sale_price": "45000",
"tags": [],
"images": [
{
"id": 56043,
"src": "pic link",
"name": "A name",
}
],
},
]
【问题讨论】:
-
请发布完整的错误消息,包括堆栈跟踪。它应该指出代码中的问题所在。此外,如果您发布了一个您尝试解析的 JSON 示例,那就太好了,因为错误表明 JSON 和模型之间的类型不匹配。
-
你在bodybytedecoded变量中解码json后得到一个列表吗?
-
@julemand101 当然,我编辑了。
-
@Diwyansh 是的,我愿意,而且图像是一个列表。
-
您的响应返回的是列表还是对象?
标签: android json flutter api dart