我使用Dio来获取响应,这是我的建模类:
import 'package:shoppingcenter/screens/homePage.dart';
class MALL {
late final int id;
late final String name;
late final String images;
MALL({required this.id, required this.name, required this.images});
factory MALL.fromJson(Map<String, dynamic> data) {
final id = data['id'];
final name = data['name'];
final images = data['images'];
return MALL(id: id, name: name, images: images);
}
}
class City {
final List<MALL> malls;
City({required this.malls});
factory City.fromJson(Map<String, dynamic> data) {
final mallData = data['malls'] as List<dynamic>?;
final malls = mallData != null ? mallData.map((mallData) => MALL.fromJson(mallData)).toList() : <MALL>[];
return City(malls: malls);
}
}
当我尝试使用我的类时,我得到这个错误:
Error: Expected a value of type 'Map<String, dynamic>', but got one of type 'String'
我的JSON是:
{
"malls": [
{
"id": 1,
"name": "city center",
"images": "city.jpg"
}
]
}
我的响应代码:
Future<List<MALL>> get() async {
final dio = Dio();
var url = 'My URL';
Response response = await dio.get(url);
City api = City.fromJson(response.data);
return api.malls;
}
我该怎么办?
2条答案
按热度按时间q5lcpyga1#
从你们的回答中我可以看出:
你的API没有返回JSON,而是返回一个HTML文件。它试图用
jsonDecode
解析html文件。用Postman检查你的API,为什么它没有返回JSON格式的响应。nx7onnlm2#
response.data
是一个String
,您需要将其解码为Map
: