A field in JSON can come in with different names, can I represent it with a single struct in Flutter?

Viewed 97

I have a JSON that can come up with a different name each time. How can I make a single factoy that receives the information regardless of the title?

factory Filmes.fromJson(Map<String, dynamic> json) {
    final title = json['original_title'];
}

depending on the API link, the title can come as 'original_title' or 'original_name'.

how can I make that '' title '' receive or one or the other? there will never be a json that comes with both options.

Thanks

Future<List<Filmes>> getFilmes({String movieOrTv}) async {
    try {
      Response response = await Dio().get(
        'https://api.themoviedb.org/3/$movieOrTv/popular?api_key=&page=1',
      );

      final json = response.data['results'];

      List<Filmes> filmes = json
          .map<Filmes>((filmesJson) => Filmes.fromJson(filmesJson))
          .toList();

      criarFilmes(filmes: filmes);
    } catch (e) {
      print(e);
      return [];
    }
  }

1 Answers

you can access the keys of your retrieved JSON and then handle the assignment using it. and you can use null operator to check values

factory Filmes.fromJson(Map<String, dynamic> json) {
print(json.keys); // here is your keys
final title = json['original_title'] ?? json['original_name'];
}
Related