The api : https://elephant-api.herokuapp.com/elephants/sex/male
returns a List of elephants in the form : [Elephant , Elephant , ... ]
while you're specifying that the json received from this request is a Map<String, dynamic>
which have a form : { elephants : [ ... ] }
so just replace every Map<String, dynamic>
with List<dynamic>
@JsonSerializable(anyMap: true)
class ElephantList{
ElephantList({this.biodata});
final List<Elephant> biodata;
factory ElephantList.fromJson(List<dynamic> json) => _$ElephantListFromJson(json);
List<dynamic> toJson() => _$ElephantListToJson(this);
}
@JsonSerializable()
class Elephant{
Elephant({this.name, this.affiliation, this.species,
this.sex, this.fictional, this.dob, this.dod, this.wikilink, this.image, this.note});
//final String index;
final String name;
final String affiliation;
final String species;
final String sex;
final String fictional;
final String dob;
final String dod;
final String wikilink;
final String image;
final String note;
factory Elephant.fromJson(Map<String, dynamic> json) => _$ElephantFromJson(json);
Map<String, dynamic> toJson() => _$ElephantToJson(this);
}
Future<ElephantList> getElephantList() async{
const url = 'https://elephant-api.herokuapp.com/elephants/sex/male';
final response = await http.get(url);
if(response.statusCode == 200){
return ElephantList.fromJson(json.decode(response.body));
}else{
throw HttpException('Error ${response.reasonPhrase}', uri: Uri.parse(url));
}
}
Edit: @JsonSerializable
expects the json as Map<string,dynamic>
, so to change the expected type you should add anyMap: true
I changed the code accordingly
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…