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

Flutter中如何解码返回数组格式的JSON?求助修正解码错误

Flutter JSON数组解码修正方案

问题根源

你的API返回的是JSON数组(多个院校对象),但当前代码尝试将整个数组解码为单个Api对象,类型完全不匹配;同时List类型的强制转换存在安全隐患,部分字段处理逻辑也有冗余。

修正后的完整代码

import 'dart:convert';
import 'package:http/http.dart' as http;

// 修正fetchData返回类型为List<Api>
Future<List<Api>> fetchData() async {
  final response = await http.get(Uri.parse(
      'http://universities.hipolabs.com/search?country=United+States'));

  if (response.statusCode == 200) {
    // 将JSON数组解码为List<dynamic>,再逐个转换为Api对象
    final List<dynamic> jsonList = jsonDecode(response.body);
    return jsonList.map((json) => Api.fromJson(json)).toList();
  } else {
    throw Exception('加载数据失败');
  }
}

class Api {
  final List<String> domains;
  final String code;
  final String country;
  final List<String> pages;
  final String name;
  final String? state;

  const Api({
    required this.domains,
    required this.code,
    required this.country,
    required this.pages,
    required this.name,
    this.state, // 可选参数,无需required,默认null
  });

  factory Api.fromJson(Map<String, dynamic> json) {
    return Api(
      // 安全转换List<dynamic>到List<String>
      domains: List<String>.from(json['domains']),
      code: json['alpha_two_code'] as String,
      country: json['country'] as String,
      pages: List<String>.from(json['web_pages']),
      name: json['name'] as String,
      // 直接赋值null,无需额外判断
      state: json['state-province'] as String?,
    );
  }
}

关键改动说明

  • 返回类型修正:fetchData的返回类型从Future<Api>改为Future<List<Api>>,匹配API返回的数组结构。
  • 数组解码逻辑:先将响应体解码为List<dynamic>,再通过map遍历每个元素,调用Api.fromJson转换为对象列表。
  • List类型安全转换:用List<String>.from()替代强制类型转换as List<String>,避免运行时类型错误。
  • 字段参数优化:state改为可选参数(去掉required),直接赋值json['state-province'] as String?,保留原始null值,无需转空字符串。

内容的提问来源于stack exchange,提问作者Raghav Sood

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:31:07