【发布时间】:2019-11-01 03:31:11
【问题描述】:
我是第一次使用api,但是我收到的json很大很复杂,所以场景如下:
- 我有一个从 api 检索到的 json 数据
- json中的数据在flutter中必须以listview的形式展示
- 我创建了一个类来映射数据:
class Anime {
int malId;
String url;
String title;
String imageUrl;
String synopsis;
String type;
String airingStart;
Null episodes;
int members;
List<Genres> genres;
String source;
List<Producers> producers;
double score;
List<String> licensors;
bool r18;
bool kids;
bool continuing;
Anime(
this.malId,
this.url,
this.title,
this.imageUrl,
this.synopsis,
this.type,
this.airingStart,
this.episodes,
this.members,
this.genres,
this.source,
this.producers,
this.score,
this.licensors,
this.r18,
this.kids,
this.continuing);
Anime.fromJson(Map<String, dynamic> json) {
malId = json['mal_id'];
url = json['url'];
title = json['title'];
imageUrl = json['image_url'];
synopsis = json['synopsis'];
type = json['type'];
airingStart = json['airing_start'];
episodes = json['episodes'];
members = json['members'];
if (json['genres'] != null) {
genres = new List<Genres>();
json['genres'].forEach((v) {
genres.add(new Genres.fromJson(v));
});
}
source = json['source'];
if (json['producers'] != null) {
producers = new List<Producers>();
json['producers'].forEach((v) {
producers.add(new Producers.fromJson(v));
});
}
score = json['score'];
licensors = json['licensors'].cast<String>();
r18 = json['r18'];
kids = json['kids'];
continuing = json['continuing'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['mal_id'] = this.malId;
data['url'] = this.url;
data['title'] = this.title;
data['image_url'] = this.imageUrl;
data['synopsis'] = this.synopsis;
data['type'] = this.type;
data['airing_start'] = this.airingStart;
data['episodes'] = this.episodes;
data['members'] = this.members;
if (this.genres != null) {
data['genres'] = this.genres.map((v) => v.toJson()).toList();
}
data['source'] = this.source;
if (this.producers != null) {
data['producers'] = this.producers.map((v) => v.toJson()).toList();
}
data['score'] = this.score;
data['licensors'] = this.licensors;
data['r18'] = this.r18;
data['kids'] = this.kids;
data['continuing'] = this.continuing;
return data;
}
}
- 这是我用来获取 json 数据的函数:
Future getdata(String season,int year) async {
var url = baseUrl + '/season/$year/${season.toString()}';
print('hitting url $url');
var response = await http.get(url);
var jsondata= jsonDecode(response.body);
}
}
- 我想要修改 getdata 函数,使其将 json 映射到我创建的类中,然后使用 futrebuilder 将其显示在列表视图中。
【问题讨论】: