我正在尝试从Flutter中的互联网获取数据。 但是我在JSON解析时遇到错误。 谁能告诉我这是什么问题?
我正在尝试从此URL获取数据
https://swapi.co/api/starships/
示例JSON
{ "count": 37, "next": "https://swapi.co/api/starships/?page=2", "previous": null, "results": [ { "name": "Executor", "model": "Executor-class star dreadnought", "manufacturer": "Kuat Drive Yards, Fondor Shipyards", "cost_in_credits": "1143350000", "length": "19000", "max_atmosphering_speed": "n/a", "crew": "279144", "passengers": "38000", "cargo_capacity": "250000000", "consumables": "6 years", "hyperdrive_rating": "2.0", "MGLT": "40", "starship_class": "Star dreadnought", "pilots": [], "films": [ "https://swapi.co/api/films/2/", "https://swapi.co/api/films/3/" ], "created": "2014-12-15T12:31:42.547000Z", "edited": "2017-04-19T10:56:06.685592Z", "url": "https://swapi.co/api/starships/15/" }, ] }
模型类
class RestModel {
final String name;
final String model;
final String manufacturer;
final String cost_in_credits;
final String length;
final String max_atmosphering_speed;
final String crew;
final String passengers;
final String cargo_capacity;
final String consumables;
final String hyperdrive_rating;
final String MGLT;
final String starship_class;
final List films;
final String pilots;
final String created;
final String edited;
final String url;
RestModel(
{this.name,
this.model,
this.manufacturer,
this.cost_in_credits,
this.length,
this.max_atmosphering_speed,
this.crew,
this.passengers,
this.cargo_capacity,
this.consumables,
this.hyperdrive_rating,
this.MGLT,
this.starship_class,
this.films,
this.pilots,
this.created,
this.edited,
this.url});
factory RestModel.fromJson(Map<String, dynamic> json) {
return RestModel(
name: json["name"],
model: json["model"],
manufacturer: json["manufacturer"],
cost_in_credits: json["cost_in_credits"],
max_atmosphering_speed: json["max_atmosphering_speed"],
crew: json["crew"],
passengers: json["passengers"],
cargo_capacity: json["cargo_capacity"],
consumables: json["consumables"],
hyperdrive_rating: json["hyperdrive_rating"],
MGLT: json["MGLT"],
starship_class: json["starship_class"],
films: json["flims"],
pilots: json["pilots"],
created: json["created"],
edited: json["edited"],
url: json["url"],
);
}
}
并且Flutter代码是:
final link = "https://swapi.co/api/starships/";
List<RestModel> list;
Future getData() async {
var res = await http
.get(Uri.encodeFull(link), headers: {"Accept":"application/json"});
if (res.statusCode == 200) {
var data = json.decode(res.body);
var rest = data["results"];
for (var model in rest) {
list.add(RestModel.fromJson(model));
}
print("List Size: ${list.length}");
}
}
主要问题是当它尝试从JSON填充数据时。
RestModel.fromJson(model)
所以我必须更改以解决此问题。
答案 0 :(得分:3)
尝试将数据'results
'投射到List
,就像这样:
var rest = data["results"] as List;
已更新
现在我们知道了错误日志:“类'RestModel'中没有声明静态方法'fromJson'”
这是因为您在此行中使用了静态方法:
list.add(RestModel.fromJson(model));
您必须更改调用才能使用工厂构造函数,如下所示:
list.add(new RestModel.fromJson(model));