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

调用API时遇Status code 401错误及JSON转Dart问题求助

问题解决:401错误及JSON转Dart对象方案

一、401 Unauthorized错误的原因及修复

你的代码出现401错误,核心原因是**x-api-key无效**:

  • 你当前填入的x-api-key值a7050c2545984437b2029d013d8a2e34,实际是URL参数里的x-endpoint-key值,并非API要求的有效x-api-key。
  • 按照错误提示,你需要登录API对应的UI界面,点击右上角的「Me」按钮,获取官方提供的合法x-api-key,替换代码中header里的对应值。

另外还要检查:

  • 确认x-endpoint-key对应的ApiConstants.docRunsEndpoint常量值是否正确,是否与API文档要求一致。
  • 确保请求头的键名拼写完全正确(比如x-api-key和x-endpoint-key的大小写、连字符不能错)。

修复后的请求头示例(替换为正确的x-api-key):

headers: {
  'x-endpoint-key': ApiConstants.docRunsEndpoint,
  'x-api-key': '你从UI获取的有效密钥',
},

二、JSON转Dart对象的两种方法

方法1:手动编写序列化/反序列化代码

假设API返回的JSON结构如下(需根据实际返回调整):

{
  "code": 200,
  "message": "success",
  "reviews": [
    {"id": 1, "content": "Great book"}
  ]
}

先定义对应的Dart类:

// Book类
class Book {
  final int code;
  final String message;
  final List<Review> reviews;

  Book({
    required this.code,
    required this.message,
    required this.reviews,
  });

  // 从JSON解析为Book对象
  factory Book.fromJson(Map<String, dynamic> json) {
    return Book(
      code: json['code'],
      message: json['message'],
      reviews: List<Review>.from(
        json['reviews'].map((reviewJson) => Review.fromJson(reviewJson)),
      ),
    );
  }
}

// 嵌套的Review类
class Review {
  final int id;
  final String content;

  Review({required this.id, required this.content});

  factory Review.fromJson(Map<String, dynamic> json) {
    return Review(
      id: json['id'],
      content: json['content'],
    );
  }
}

然后在你的fetchBookReviews方法中,直接调用Book.fromJson(jsonResponse)即可完成转换。

方法2:使用json_serializable自动生成代码(推荐)

对于复杂结构,手动编写容易出错,可借助第三方包自动生成代码:

  1. 在pubspec.yaml中添加依赖:
dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.6
  json_serializable: ^6.7.1
  1. 定义带注解的Dart类(以Book为例):
import 'package:json_annotation/json_annotation.dart';

// 生成的代码会存放在这个文件里
part 'book.g.dart';

@JsonSerializable()
class Book {
  final int code;
  final String message;
  final List<Review> reviews;

  Book({
    required this.code,
    required this.message,
    required this.reviews,
  });

  // 自动生成的fromJson方法
  factory Book.fromJson(Map<String, dynamic> json) => _$BookFromJson(json);

  // 自动生成的toJson方法(可选)
  Map<String, dynamic> toJson() => _$BookToJson(json);
}

@JsonSerializable()
class Review {
  final int id;
  final String content;

  Review({required this.id, required this.content});

  factory Review.fromJson(Map<String, dynamic> json) => _$ReviewFromJson(json);
  Map<String, dynamic> toJson() => _$ReviewToJson(json);
}
  1. 运行命令生成序列化代码:
flutter pub run build_runner build

生成完成后,就可以像手动编写一样调用Book.fromJson(jsonResponse)完成转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:50:35