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

Flutter模型如何从数组嵌套对象中获取数据?

解决方法

你的问题出在两点:一是没处理JSON里嵌套的general_info对象,直接从根节点取area和datev肯定拿不到值;二是外层JSON包含一个cadastres数组,需要先遍历这个数组再逐个解析成Cadastre实例。

1. 修正Cadastre模型的解析逻辑

先修改Cadastre的fromJson方法,从general_info子对象里提取数据:

class Cadastre {
  final int id;
  final double area;
  final String creationDate;

  Cadastre({
    required this.id,
    required this.area,
    required this.creationDate,
  });

  // 传入外层JSON的id值,作为每个Cadastre的id
  factory Cadastre.fromJson(Map<String, dynamic> itemJson, int globalId) {
    // 先取出嵌套的general_info子对象
    final generalInfo = itemJson['general_info'] as Map<String, dynamic>;
    return Cadastre(
      id: globalId,
      // 从general_info里取area和datev
      area: generalInfo['area'].toDouble(), // 若JSON中是整数,转成double类型
      creationDate: generalInfo['datev'] as String,
    );
  }
}

2. 解析整个JSON结构

外层JSON包含id和cadastres数组,需要先解析顶层数据,再遍历数组生成Cadastre列表:

// 解析完整JSON的方法
List<Cadastre> parseCadastreData(Map<String, dynamic> json) {
  final globalId = json['id'] as int;
  final cadastreItems = json['cadastres'] as List<dynamic>;

  // 遍历数组,逐个生成Cadastre实例
  return cadastreItems
      .map((item) => Cadastre.fromJson(item, globalId))
      .toList();
}

可选:用顶层模型包裹全局数据

如果外层的id是整个响应的标识,而非每个地籍的属性,可以创建一个顶层模型来统一管理:

// 顶层响应模型
class CadastreResponse {
  final int responseId;
  final List<Cadastre> cadastres;

  CadastreResponse({
    required this.responseId,
    required this.cadastres,
  });

  factory CadastreResponse.fromJson(Map<String, dynamic> json) {
    final cadastreItems = json['cadastres'] as List<dynamic>;
    return CadastreResponse(
      responseId: json['id'] as int,
      cadastres: cadastreItems
          .map((item) {
            final generalInfo = item['general_info'] as Map<String, dynamic>;
            return Cadastre(
              area: generalInfo['area'].toDouble(),
              creationDate: generalInfo['datev'] as String,
            );
          })
          .toList(),
    );
  }
}

// 调整后的Cadastre模型(去掉id字段)
class Cadastre {
  final double area;
  final String creationDate;

  Cadastre({
    required this.area,
    required this.creationDate,
  });
}

调用示例:

// 假设已将JSON字符串转为Map
final jsonMap = jsonDecode(yourJsonString);
final response = CadastreResponse.fromJson(jsonMap);
// response.cadastres即为所有地籍数据的列表

内容的提问来源于stack exchange,提问作者Flutter kyoto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:30:50