我正在制作一个Flutter 应用程序,我正在使用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>岁的子元素,因为关键字dynamic不意味着any对象吗?有人知道如何将嵌套的JSON数组解析为自定义对象吗?

推荐答案

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

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

看看https://flutter.io/json/,从中可以找到一些提示.

有一些解决方案,比如https://pub.dartlang.org/packages/json_serializable个,可以让这件事变得容易得多

Flutter相关问答推荐

Firebase Auth异常未被catch捕获

使用自定义控制器将项插入到ListView中时行为不正确

如何处理Flutter Riverpod异步通知器中的状态和数据库

为什么当我使用Riverpod更新状态时,列表会被刷新?

不要跨同步间隔使用BuildContext

Flutter中的编译时间常量方法

如何在巡逻测试期间重新启动dart 侧应用程序状态?

如何手动将 FirebaseAuth 用户邮箱验证状态设置为 true

Flutter 需要 Xcode 14 或更高版本

如何在flutter中更改showModalBottomSheet小部件中CheckboxListTile小部件的值?

Flutter记录返回类型问题

显示图像的放大部分

Flutter应用无法上传到Microsoft Store

如何使用Riverpod提供程序正确构建搜索栏?

如何解决需要一个标识符,但得到的是:.try 在:之前插入一个标识符.dart 错误

小部件堆栈未显示顶层

Flutter - 如何将按钮对齐到行的右侧

Android Electric eel Mac M1:运行 flutter doctor -v 时无法找到Bundle 的 java 版本

无法将参数类型Future Function(String?)分配给参数类型void Function(NotificationResponse)?

有什么方法可以将 ChangeNotifier 与 ValueListenableBuilder 一起使用