我的JSON有点像这样:
{"data":{"id":1,"title":"Title 1", "images": [{"small": "link", "large": "link"}]}}
我的模型类:
class Test {
final int id;
final String title;
final Images images;
Test({required this.id,
required this.title,
required this.images});
Test.fromJson(Map<dynamic, dynamic> parsedJson) :
id = parsedJson["id"],
title = parsedJson["title"],
images = Images.fromJson(parsedJson['images']);
class Images {
final String small;
final String large;
Images({
required this.small,
required this.large
});
factory Images.fromJson(Map<dynamic, dynamic> json) {
return Images(
small : json["small"] as String,
large : json["large"] as String
);}
}下面是我的api调用:
static Future<Test> getTest(int id) async{
final response = await http.get(Uri.parse("url_here"));
if(response.statusCode == 200){
Map<String, dynamic> json = jsonDecode(response.body);
dynamic body = json['data'];
Test test = Test.fromJson(body);
return test;
}
else{
throw("message");
}
}如何在视图类中获得images.small?如果我需要澄清我的问题,请告诉我。我得到的错误列表不是Map类型的子类型,而是试图获取图像,但我无法将映射隐藏到列表中。
发布于 2021-06-25 08:02:55
你可以试着使用这个模型。:
import 'dart:convert';
Test testFromJson(String str) => Test.fromJson(json.decode(str));
String testToJson(Test data) => json.encode(data.toJson());
class Test {
Test({
this.id,
this.title,
this.images,
});
int id;
String title;
List<Images> images;
factory Test.fromJson(Map<String, dynamic> json) => Test(
id: json["id"],
title: json["title"],
images: List<Images>.from(json["images"].map((x) => Images.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"images": List<dynamic>.from(images.map((x) => x.toJson())),
};
}
class Images {
Images({
this.small,
this.large,
});
String small;
String large;
factory Images.fromJson(Map<String, dynamic> json) => Images(
small: json["small"],
large: json["large"],
);
Map<String, dynamic> toJson() => {
"small": small,
"large": large,
};
}在这里,图像列表已经直接映射到相应的images对象,从而解决了您的问题。
发布于 2021-06-25 08:04:00
"images": [{"small": "link", "large": "link"}],这是一个列表映射,您正在将它转换为字符串映射。
要么使用"images": {"small": "link", "large": "link"}
或使用
factory Images.fromJson(List<dynamic> json) {
return Images(
small : json[0]["small"] as String,
large : json[0]["large"] as String
);}https://stackoverflow.com/questions/68127285
复制相似问题