67 lines
1.7 KiB
Dart
67 lines
1.7 KiB
Dart
import 'dart:convert';
|
|
import 'package:json_annotation/json_annotation.dart';
|
|
import 'package:fixnum/fixnum.dart'; // 用于处理 Int64 类型
|
|
|
|
part 'ApiResponse.g.dart';
|
|
|
|
@JsonSerializable(genericArgumentFactories: true)
|
|
class ApiResponse<T> {
|
|
int? code;
|
|
int? total;
|
|
T? data;
|
|
String? message;
|
|
|
|
ApiResponse();
|
|
|
|
// JSON 反序列化
|
|
factory ApiResponse.fromJson(
|
|
Map<String, dynamic> json,
|
|
T Function(Object? json) fromJsonT,
|
|
) =>
|
|
_$ApiResponseFromJson(json, fromJsonT);
|
|
|
|
// JSON 序列化
|
|
Map<String, dynamic> toJson(Object? Function(T value) toJsonT) =>
|
|
_$ApiResponseToJson(this, toJsonT);
|
|
|
|
// 添加自定义的 toJson 序列化方法,确保能正确序列化泛型数据
|
|
String serialize() {
|
|
// 手动处理 data 中的 Int64 转换为 int
|
|
var serializedData = _serializeData(data);
|
|
return jsonEncode({
|
|
'code': code,
|
|
'total': total,
|
|
'data': serializedData,
|
|
'message': message,
|
|
});
|
|
}
|
|
|
|
// 递归处理 data 中的每个项,转换 Int64 为 int
|
|
dynamic _serializeData(dynamic data) {
|
|
if (data is List) {
|
|
// 处理 List 中的 Int64 类型
|
|
return data.map((e) => _serializeData(e)).toList();
|
|
} else if (data is Map) {
|
|
// 处理 Map 中的 Int64 类型
|
|
var map = Map<String, dynamic>.from(data);
|
|
map.forEach((key, value) {
|
|
if (value is Int64) {
|
|
map[key] = value.toInt();
|
|
} else {
|
|
map[key] = _serializeData(value);
|
|
}
|
|
});
|
|
return map;
|
|
} else if (data is Int64) {
|
|
// 如果是 Int64 类型,转换为 int
|
|
return data.toInt();
|
|
}
|
|
return data;
|
|
}
|
|
|
|
@override
|
|
String toString() {
|
|
return serialize();
|
|
}
|
|
}
|