rak*_*das 12 json dart flutter
我正在制作一个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",
...
}
Run Code Online (Sandbox Code Playgroud)
我已经设置了一个模型类来解析它,并且类定义如下:
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'];
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我无法从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
Run Code Online (Sandbox Code Playgroud)
我认为这会有效,因为我为Genre对象创建了一个不同的类,并将JSON数组作为列表传递.我不明白怎么List<dynamic>不是孩子,List<Genre>因为关键词不是dynamic暗示任何对象?有谁知道如何将嵌套的JSON数组解析为自定义对象?
Kev*_*ore 24
尝试 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,这使得这更容易
| 归档时间: |
|
| 查看次数: |
11007 次 |
| 最近记录: |