json_serializable.dart
json_serializable.dart copied to clipboard
Convert json list to Object in Generic class
Hi. I am having trouble in converting a json returned from API to the respective model. I am using the Generic class. When I try to parse T.fromJson(x)
it gives me an error i.e. The method 'fromJson' isn't defined for the type 'Type'
. I saw another package simple_json that provides this facility and I am able to get the required object list when I deserialize the json. But I want to use the json_serializeable
package and look if it provides this functionality or do I need to do something custom to achieve this?
class APIHandler<T> {
Future<List<T>> getAllAsync(String endpoint) async {
try {
http.Response response;
response = await http.get(Uri.parse(endpoint));
if (response.statusCode == 200) {
List<T> list =
List<T>.from(json.decode(response.body).map((x) => T.fromJson(x)));
return list;
} else
return [];
} catch (_) {
rethrow;
}
}
}
I'm using this solution:
final List<Map<String, dynamic>> list = json.decode(response.body).cast<Map<String, dynamic>>();
List<Product> result = list.map(Product.fromJson).toList();
What @eximius313 said!