颤振索引Json数据



我不想索引json像(json["features"][0]json["features"][1])。我怎么能把它列个清单什么的呢?

我的代码如下:

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数据在这里:https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson

您可以重构代码:

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'],
);
}

或者使用像这样的插件为你的实体生成JSON解析器。

关于如何使用JSON的更多信息包含在官方Flutter文档中。

最新更新