【问题标题】:Flutter Indexing Json DatasFlutter 索引 Json 数据
【发布时间】:2021-05-04 05:20:30
【问题描述】:

我不想像 (json["features"][0]json["features"][1]) 这样索引 json。我怎样才能把它变成一个列表或其他东西?

我的代码如下:

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

【问题讨论】:

    标签: android json list flutter mobile


    【解决方案1】:

    你可以重构你的代码:

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

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

    有关如何使用 JSON 的更多信息包含在 Official Flutter Documentation 中。

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 2013-02-07
      • 2023-01-09
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2020-04-14
      相关资源
      最近更新 更多