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

Flutter中Dio请求因后端混有PHP警告无法解析JSON的解决办法

解决Flutter Dio请求时因PHP警告导致JSON解析失败的问题

问题核心是服务器返回内容并非纯JSON,开头夹杂了PHP警告的HTML代码(比如<br />开头的错误信息),导致Dio自动解析JSON时抛出格式异常。由于无法修复后端,可在Flutter端手动处理响应内容:

解决步骤

  1. 修改响应类型:将Dio的ResponseType.json改为ResponseType.plain,让Dio直接返回原始字符串,避免自动解析触发异常。
  2. 提取合法JSON:从原始响应字符串中定位到合法JSON的起始位置(通常是第一个{或[),截取之后的纯JSON内容。
  3. 手动解析JSON:将截取后的字符串手动解析为可使用的对象。

修改后的代码示例

import 'dart:convert';
import 'package:dio/dio.dart';

Future<dynamic> getMethod(String url) async {
  Dio dio = Dio();
  dio.options.headers['content-type'] = 'application/json';
  
  // 请求原始文本,跳过自动JSON解析
  final response = await dio.get(
    url,
    options: Options(responseType: ResponseType.plain, method: 'GET'),
  );

  if (response.statusCode == 200) {
    String rawResponse = response.data.toString();
    
    // 定位JSON起始位置,优先找{,找不到再找[
    int jsonStartIndex = rawResponse.indexOf('{');
    if (jsonStartIndex == -1) {
      jsonStartIndex = rawResponse.indexOf('[');
    }

    if (jsonStartIndex != -1) {
      // 截取纯JSON部分
      String pureJson = rawResponse.substring(jsonStartIndex);
      try {
        // 手动解析JSON
        return jsonDecode(pureJson);
      } catch (e) {
        throw Exception('JSON解析失败: $e');
      }
    } else {
      throw Exception('响应中未找到合法JSON结构');
    }
  } else {
    throw Exception('请求失败,状态码: ${response.statusCode}');
  }
}

补充说明

  • 如果PHP警告格式固定(比如都是以<br />开头的多行内容),也可以用正则表达式批量移除警告,例如:rawResponse.replaceAll(RegExp(r'^<br />.*?(?={|\[)'), ''),需根据实际警告格式调整正则规则。
  • 务必保留异常捕获逻辑,避免因响应格式意外变化导致APP崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:12:13