json_serializable.dart icon indicating copy to clipboard operation
json_serializable.dart copied to clipboard

Convert json list to Object in Generic class

Open Lyba97 opened this issue 1 year ago • 1 comments

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;
    }
  }
}

Lyba97 avatar Aug 02 '22 08:08 Lyba97

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();

eximius313 avatar Aug 13 '22 00:08 eximius313

What @eximius313 said!

kevmoo avatar Oct 04 '22 02:10 kevmoo