CloudWindMoonSun
CloudWindMoonSun

Reputation: 392

How to avoid so many casting and mapping while converting json to a list of objects in Dart?

In Dart (Flutter), I want to create a list of 'Currency' objects from an api endpoint that creates a json similar to this:

{
 "AED": "United Arab Emirates Dirham",
 "AFN": "Afghan Afghani",
 "ALL": "Albanian Lek",
 "AMD": "Armenian Dram",
 "ANG": "Netherlands Antillean Guilder",
 ...
 ...
}

My 'Currency' class is just simply:

class Currency {
  String code;
  String fullName;
  Currency(this.code, this.fullName);
}

I use the following method to get the list currencies in Json format and then create a list of currency objects:

Future<List<Currency>> getCurrencies() async {
   final http.Client client = http.Client();
   final String uri = "https://openexchangerates.org/api/currencies.json";
   return await client
    .get(uri)
    .then((response) 
      {
        var jsonEntries = (json.decode(response.body) as Map<String, dynamic>).entries.toList();
        var currencyEntries = jsonEntries.map((x) => new Currency(x.key, "", x.value));
        return currencyEntries.toList();
      })
    .catchError((e) => print(e))
    .whenComplete(() => client.close());
}

There must be more efficient ways to do this. I had to do many mapping, casting, toListing to create objects from this simple Json string.

How can I achieve this in a shorter, more efficient way?

Upvotes: 0

Views: 94

Answers (1)

Nate Bosch
Nate Bosch

Reputation: 10925

You might want to look in to code generation approaches like json_serializable. The necessity of casting and mapping to get strongly typed objects from JSON is a known pain point, but there are no current solutions at the language level.

Upvotes: 1

Related Questions