I don't want to index the json like (json["features"][0]
or json["features"][1])
. How can I instead make this a list or something?
My code is below:
class Other {
String title;
double mag;
String title1;
double mag1;
String title2;
double mag2;
Other({this.mag, this.title, this.mag1, this.title1, this.mag2, this.title2});
factory Other.fromJson(Map<String, dynamic> json) {
return Other(
title: json["features"][0]["properties"]["place"],
mag: json["features"][0]["properties"]["mag"],
title1: json["features"][1]["properties"]["place"],
mag1: json["features"][1]["properties"]["mag"],
title2: json["features"][2]["properties"]["place"],
mag2: json["features"][2]["properties"]["mag"],
);
}
}
json datas is here: https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson
You can refactor your code:
factory Other.fromJson(Map<String, dynamic> json) {
final features = json['features'];
final firstProperties = reatures[0]['properties'];
final secondProperties = reatures[0]['properties'];
final thirdProperties = reatures[0]['properties'];
return Other(
title: firstProperties['place'],
mag: firstProperties['mag'],
title1: secondProperties['place'],
mag1: secondProperties['mag'],
title2: thirdProperties['place'],
mag2: thirdProperties['mag'],
);
}
Or use plugins like this one that generate JSON parser for your entity.
More information about how to work with JSON contains in Official Flutter Documentation .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.