首页 > 解决方案 > 如何将 GeoJSON 解析为 Dart/Flutter 中的类型

问题描述

我的服务器上有这样的 JSON:

        {
          "coordinates": [
            [
              [
                -122.41251225499991,
                37.78047851100007
              ],
              [
                -122.42194124699989,
                37.77303605000009
              ],
              ...trimmed...
              [
                -122.41251225499991,
                37.78047851100007
              ]
            ]
          ],
          "crs": {
            "properties": {
              "name": "EPSG:4326"
            },
            "type": "name"
          },
          "type": "Polygon"
        }

我想在我的服务器上解析它,但我不知道该怎么做。我找到了两个适用于 GeoJSON 的 Dart 库:

geojson https://pub.dev/packages/geojson geojson_vi https://pub.dev/packages/geojson_vi

这两个都只有从字符串函数解析,但我有一张地图。在 Dart/Flutter 中解析此类内容的最佳方法是什么?

标签: flutterdart

解决方案


是这个意思吗?

class GetJsonData{
    GetJsonData({
        this.coordinates,
        this.crs,
        this.type,
    });

    List<List<List<double>>> coordinates;
    Crs crs;
    String type;

    factory GetVehicleInfo.fromJson(Map<String, dynamic> json) => GetVehicleInfo(
        coordinates: List<List<List<double>>>.from(json["coordinates"].map((x) => List<List<double>>.from(x.map((x) => List<double>.from(x.map((x) => x.toDouble())))))),
        crs: Crs.fromJson(json["crs"]),
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "coordinates": List<dynamic>.from(coordinates.map((x) => List<dynamic>.from(x.map((x) => List<dynamic>.from(x.map((x) => x)))))),
        "crs": crs.toJson(),
        "type": type,
    };
}

class Crs {
    Crs({
        this.properties,
        this.type,
    });

    Properties properties;
    String type;

    factory Crs.fromJson(Map<String, dynamic> json) => Crs(
        properties: Properties.fromJson(json["properties"]),
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "properties": properties.toJson(),
        "type": type,
    };
}

class Properties {
    Properties({
        this.name,
    });

    String name;

    factory Properties.fromJson(Map<String, dynamic> json) => Properties(
        name: json["name"],
    );

    Map<String, dynamic> toJson() => {
        "name": name,
    };
}


推荐阅读