之前的文章記錄了解析簡單json的方法、今天遇到復雜的格式、記錄作為參考
接口:http://news-at.zhihu.com/api/4/news/latest (知乎開放接口)
數(shù)據(jù)格式:


json分析: 包含一string字符串兩個list,所以要建立兩個class分別為top_stories、stories,其中top_stories的images為數(shù)組所以要使用 list<String>?images這種方式
bean類:
import 'package:json_annotation/json_annotation.dart';
part 'Sydata.g.dart';
@JsonSerializable()
class Sysdata? {
final String date;
final List<Staets> stories;
@JsonKey(name: "top_storie")
final List<Topstate> topstories;
Sysdata({this.date,this.stories,this.topstories});
? factory Sysdata.fromJson(Map<String,dynamic> parms) =>_$SysdataFromJson(parms);
? Map<String,dynamic> toJson() => _$SysdataToJson(this);
}
@JsonSerializable()
class Staets {
List <String> images;
int type;
int id;
@JsonKey(name: "ga_prefix")
String gaprefix;
String title;
Staets({this.images,this.type,this.id,this.gaprefix,this.title});
factory Staets.fromJson(Map<String,dynamic> parms) => _$StaetsFromJson(parms);
Map<String,dynamic> toJson() =>_$StaetsToJson(this);
}
@JsonSerializable()
class Topstate{
? String image;
? int type;
? int id;
? @JsonKey(name: "ga_prefix")
? String gaprefix;
? String title;
? Topstate({this.image,this.type,this.id,this.gaprefix,this.title});
? factory Topstate.fromJson(Map<String,dynamic> parms) =>_$TopstateFromJson(parms);
? Map <String,dynamic> toJson() =>_$TopstateToJson(this);
}
注意dart并不能直接轉(zhuǎn)譯 “xx-xx”字符串所以使用?@JsonKey(name:"") 進行包裹
解析方法:
