You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSON转Dart类出现3个序列化错误,寻求修复方案

JSON转Dart类时出现List序列化错误

错误详情

转换JSON为Dart类后出现3个关联错误,错误提示为'The method 'toJson' isn't defined for the type 'List'',具体报错位置:

  • Geojson类的fromJson方法中调用List.fromJson(v)
  • Geojson类的toJson方法中调用v.toJson()
  • 自动生成的空Coordinates类无实际作用

报错代码

class RedZoneModel {
    bool? status;
    List<Data>? data;

    RedZoneModel({this.status, this.data});

    RedZoneModel.fromJson(Map<String, dynamic> json) {
        status = json['status'];
        if (json['data'] != null) {
            data = <Data>[];
            json['data'].forEach((v) { data!.add(new Data.fromJson(v)); });
        }
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['status'] = this.status;
        if (this.data != null) {
            data['data'] = this.data!.map((v) => v.toJson()).toList();
        }
        return data;
    }
}

class Data {
    int? id;
    String? areaName;
    Geojson? geojson;
    String? createdAt;
    String? updatedAt;

    Data({this.id, this.areaName, this.geojson, this.createdAt, this.updatedAt});

    Data.fromJson(Map<String, dynamic> json) {
        id = json['id'];
        areaName = json['area_name'];
        geojson = json['geojson'] != null ? new Geojson.fromJson(json['geojson']) : null;
        createdAt = json['created_at'];
        updatedAt = json['updated_at'];
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['area_name'] = this.areaName;
        if (this.geojson != null) {
            data['geojson'] = this.geojson!.toJson();
        }
        data['created_at'] = this.createdAt;
        data['updated_at'] = this.updatedAt;
        return data;
    }
}

class Geojson {
    String? type;
    List<List>? coordinates;

    Geojson({this.type, this.coordinates});

    Geojson.fromJson(Map<String, dynamic> json) {
        type = json['type'];
        if (json['coordinates'] != null) {
            coordinates = <List>[];
            json['coordinates'].forEach((v) { coordinates!.add(new List.fromJson(v)); }); // ! 错误位置
        }
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['type'] = this.type;
        if (this.coordinates != null) {
            data['coordinates'] = this.coordinates!.map((v) => v.toJson()).toList(); // ! 错误位置
        }
        return data;
    }
}

class Coordinates {
    Coordinates({ }); // ! 错误位置

    Coordinates.fromJson(Map<String, dynamic> json) {
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        return data;
    }
}

原始JSON响应

{
    "status": true,
    "data": [
        {
            "id": 8,
            "area_name": "Surian",
            "geojson": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            -1.2453052,
                            460.8429751
                        ],
                        [
                            -1.2200768,
                            460.9066456
                        ],
                        [
                            -1.2564606,
                            460.9423423
                        ],
                        [
                            -1.2940451,
                            460.8711205
                        ],
                        [
                            -1.2453052,
                            460.8429751
                        ],
                        [
                            -1.2940451,
                            460.8711205
                        ],
                        [
                            -1.2453052,
                            460.8429751
                        ]
                    ]
                ]
            },
            "created_at": "2022-08-29T14:30:10.000000Z",
            "updated_at": "2022-12-19T18:30:10.000000Z"
        },
        {
            "id": 13,
            "area_name": "test edit",
            "geojson": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            123,
                            123
                        ],
                        [
                            123,
                            123
                        ],
                        [
                            123,
                            123
                        ],
                        [
                            123,
                            123
                        ],
                        [
                            123,
                            123
                        ]
                    ]
                ]
            },
            "created_at": "2022-08-29T15:43:35.000000Z",
            "updated_at": "2022-12-20T08:28:00.000000Z"
        }
    ]
}

解决建议

1. 修正Geojson类的坐标处理逻辑

原始JSON中coordinates是三层嵌套的数值列表(List<List<List<double>>>),Dart的List不存在fromJson或toJson方法,直接做类型转换即可。修改后的Geojson类:

class Geojson {
  String? type;
  List<List<List<double>>>? coordinates;

  Geojson({this.type, this.coordinates});

  Geojson.fromJson(Map<String, dynamic> json) {
    type = json['type'];
    // 逐层转换嵌套列表的类型
    coordinates = (json['coordinates'] as List?)
        ?.map((outerList) => (outerList as List)
            .map((midList) => (midList as List).map((numVal) => numVal as double).toList())
            .toList())
        .toList();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['type'] = type;
    // 直接赋值嵌套列表,不需要额外调用toJson
    data['coordinates'] = coordinates;
    return data;
  }
}

2. 删除无用的Coordinates类

自动生成的空Coordinates类完全没有实际用途,直接删除即可。

3. 优化代码的空安全与简洁性

替换forEach循环为map构建列表,让代码更简洁且符合Dart最佳实践:

  • RedZoneModel的fromJson优化:
RedZoneModel.fromJson(Map<String, dynamic> json)
    : status = json['status'],
      data = (json['data'] as List?)?.map((item) => Data.fromJson(item)).toList();
  • Data类的fromJson优化:
Data.fromJson(Map<String, dynamic> json)
    : id = json['id'],
      areaName = json['area_name'],
      geojson = json['geojson'] != null ? Geojson.fromJson(json['geojson']) : null,
      createdAt = json['created_at'],
      updatedAt = json['updated_at'];

内容的提问来源于stack exchange,提问作者Danish Maula

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 11:02:11