我想从响应中获取Map
我的对象是
class Product{
String id;
String title;
double price;
String image;
bool sc;
Product({@required this.id, @required this.title, @required this.price,
@required this.image, @required this.sc});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'] as String,
title: json['title'] as String,
price: json['price'] as double,
image: json['image'] as String,
sc: json['sc'] as bool,
);
}
}
Http代码在这里
Future<Map<String, List<Product>>> fetchProduct(String url) async{
dio.Dio d = new dio.Dio();
Map<String, dynamic> headers = new Map();
headers['Cookie'] = "JSESSIONID=" + SessionUtils().getSession().toString();
dio.Options options = new dio.Options(
headers: headers,
contentType: 'application/json'
);
dio.Response response = await d.get(url, options: options);
print(response.data);
if(response.statusCode == HttpStatus.ok){
return json.decode(response.data); // need help here
}
}
我遇到了错误I/flutter (20085): Another exception was thrown: type '_TypeError' is not a subtype of type 'String'
谢谢!
答案 0 :(得分:0)
在他们的API参考中,他们提到您必须在选项中设置responseType。默认值为JSON,因此也许您可以直接返回response.data,因为它已经反序列化到地图中。
另一个选项可能是:
responseType = responseType.string;
在dio选项中,您将获得可以手动解码的字符串形式的response.data。
我从未使用过DIO,但根据API参考,这似乎是问题所在,因为该错误表明json.decode()需要一个字符串但得到了一个映射,因此response.data是动态的,并且数据类型基于在指定的responseType上。试试看!