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

PHP json_encode返回对象列表,Flutter json.decode无法识别有效JSON

Flutter解码JSON响应报错:响应被识别为列表而非JSON字符串

问题描述

  • PHP接口经json_encode()处理后,在Live Server中以列表对象形式返回
  • 查看源代码显示为有效JSON,且已通过jsonlint验证
  • Flutter中解码响应时出错,系统将响应识别为列表而非JSON字符串

附上的PHP代码

config.php

<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', '');


// create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$is_utf_8 = $conn->set_charset("utf8");

// check connection
if ($conn->connect_error) {
    die('Connection Failed ' . $conn->connect_error);
}

fetch_users.php

<?php
header('Content-Type: application/json; charset=utf-8');
header('Accept: application/json');
header('Allow: GET');
include 'config.php';

$sql = "SELECT * FROM Users";
$result = $conn->query($sql);

$list = array();
while ($rows = $result->fetch_assoc()){
    $list[] = $rows;
}
echo json_encode($list);

解决方案

你的PHP接口返回的确实是JSON数组(列表),Flutter报错的核心原因是你用了解码对象的逻辑去解析数组。按以下步骤修改即可解决:

  1. 正确解码JSON数组
    不要尝试将响应直接解析为单个对象,先解码为列表,再转换为自定义模型:

    final response = await http.get(Uri.parse('你的接口地址'));
    if (response.statusCode == 200) {
        // 解码为动态列表
        List<dynamic> rawList = jsonDecode(response.body);
        // 转换为User模型列表
        List<User> users = rawList.map((item) => User.fromJson(item)).toList();
    }
    
  2. 定义对应模型类
    根据数据库表结构创建User模型,适配解析逻辑:

    class User {
      final int id;
      final String username;
      // 补充Users表的其他字段
    
      User({required this.id, required this.username});
    
      factory User.fromJson(Map<String, dynamic> json) {
        return User(
          id: json['id'],
          username: json['username'],
          // 映射其余字段
        );
      }
    }
    
  3. PHP端额外优化

    • 避免输出多余字符(如BOM头、空格),在输出JSON前清空缓冲区:
      ob_clean();
      echo json_encode($list);
      
    • 检测JSON编码错误,方便排查问题:
      $jsonData = json_encode($list);
      if (json_last_error() !== JSON_ERROR_NONE) {
          die(json_last_error_msg());
      }
      echo $jsonData;
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:35:19