json - 在 Dart 中解析具有嵌套对象数组的 JSON?

我正在制作一个 Flutter 应用程序,并且我正在使用 The MovieDB api 来获取数据。当我调用 api 并要求特定电影时,这是我返回的一般格式:

{
   "adult": false,
    "backdrop_path": "/wrqUiMXttHE4UBFMhLHlN601MZh.jpg",
    "belongs_to_collection": null,
    "budget": 120000000,
    "genres": [
        {
            "id": 28,
            "name": "Action"
        },
        {
            "id": 12,
            "name": "Adventure"
        },
        {
            "id": 878,
            "name": "Science Fiction"
        }
    ],
    "homepage": "http://www.rampagethemovie.com",
    "id": 427641,
    "imdb_id": "tt2231461",
    "original_language": "en",
    "original_title": "Rampage",
...
}

我已经设置了一个模型类来解析这个,这个类是这样定义的:

import 'dart:async';

class MovieDetail {
  final String title;
  final double rating;
  final String posterArtUrl;
  final backgroundArtUrl;
  final List<Genre> genres;
  final String overview;
  final String tagline;
  final int id;

  const MovieDetail(
      {this.title, this.rating, this.posterArtUrl, this.backgroundArtUrl, this.genres, this.overview, this.tagline, this.id});

  MovieDetail.fromJson(Map jsonMap)
      : title = jsonMap['title'],
        rating = jsonMap['vote_average'].toDouble(),
        posterArtUrl = "http://image.tmdb.org/t/p/w342" + jsonMap['backdrop_path'],
        backgroundArtUrl = "http://image.tmdb.org/t/p/w500" + jsonMap['poster_path'],
        genres = (jsonMap['genres']).map((i) => Genre.fromJson(i)).toList(),
        overview = jsonMap['overview'],
        tagline = jsonMap['tagline'],
        id = jsonMap['id'];
}
class Genre {
  final int id;
  final String genre;

  const Genre(this.id, this.genre);

  Genre.fromJson(Map jsonMap)
    : id = jsonMap['id'],
      genre = jsonMap['name'];
}

我的问题是我无法从 JSON 中正确解析流派。当我获取 JSON 并将其传递给我的模型类时,我收到以下错误:

I/flutter (10874): type 'List<dynamic>' is not a subtype of type 'List<Genre>' where
I/flutter (10874):   List is from dart:core
I/flutter (10874):   List is from dart:core
I/flutter (10874):   Genre is from package:flutter_app_first/models/movieDetail.dart

我认为这会起作用,因为我为 Genre 创建了一个不同的类对象并作为列表传入 JSON 数组。我不明白 List<dynamic>不是 List<Genre> 的 child 因为不是关键字dynamic暗示任何对象?有谁知道如何将嵌套的 JSON 数组解析为自定义对象?

最佳答案

试试genres = (jsonMap['genres'] as List).map((i) => Genre.fromJson(i)).toList()

问题:在没有强制转换的情况下调用 map 使其成为动态调用,这意味着 Genre.fromJson 的返回类型也是动态的(不是 Genre)。

看看https://flutter.io/json/一些提示。

有一些解决方案,例如 https://pub.dartlang.org/packages/json_serializable ,这让这变得更容易了

https://stackoverflow.com/questions/50360443/

相关文章:

flutter - Flutter 中的 MyApp 类错误未定义方法 'setState'

android - 如何在 Flutter 中禁用 FlatButton 的飞溅突出显示?

android - 在 Flutter 项目的 android studio 上初始化 Gradle

android - 在 Android Studio 中开发的 Flutter 项目的合法 .git

dart - 如何格式化内插字符串

google-cloud-firestore - 如何使用 Flutter 配置 Firebase

dart - Flutter 从 Firebase 存储加载图像

dart - 测试使用插件和平台 channel 的 Flutter 代码

swift - 如何在 Flutter 中启用对现有项目的 Swift 支持

dart - 使用 BLoC 处理导航的正确方法