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

Dart向服务器发送数据模型时无法声明UnsignedInt类型

问题

我在数据模型中定义了UnsignedInt? countryID字段,但向服务器发送该模型时,json_serializable无法生成对应的序列化代码,报错信息如下:

[SEVERE] json_serializable:json_serializable on lib/src/model/otp.dart (cached):
Could not generate fromJson code for countryID. To support the type UnsignedInt you can:

  • Use JsonConverter
  • Use JsonKey fields fromJson and toJson
    package:myapp/src/model/otp.dart:18:16 ╷
    18 │ UnsignedInt? countryID;
    │ ^^^^^^^^^
    ╵
    [SEVERE] Failed after 103ms
    pub finished with exit code 1

发送模型的代码如下:

Future<OTP?> getCode(String countryCode, String phone) async {
    const url = HttpUtils.baseUrl + HttpUtils.getcode;
    _myOtp = null;
    try {
      final response = await http.post(
        Uri.parse(url),
        headers: {"Content-Type": "application/json"},
        body: json.encode(OTP(phoneNo: phone,).toJson()),
      );
      _myOtp = OTP.fromJson(json.decode(response.body)["otp"]);
    } catch (error) {
      if (kDebugMode) {
        print(error.toString());
      }
    }
    return _myOtp;
  }
解决办法

方案1:自定义JsonConverter

创建转换器类,处理UnsignedInt与JSON数据的双向转换:

class UnsignedIntConverter implements JsonConverter<UnsignedInt?, dynamic> {
  const UnsignedIntConverter();

  @override
  UnsignedInt? fromJson(dynamic json) {
    if (json is int) {
      return UnsignedInt.fromInt(json);
    }
    return null;
  }

  @override
  dynamic toJson(UnsignedInt? object) {
    return object?.toInt();
  }
}

然后在OTP模型类上标注该转换器:

@JsonSerializable()
@UnsignedIntConverter()
class OTP {
  UnsignedInt? countryID;
  String? phoneNo;

  OTP({this.countryID, this.phoneNo});

  factory OTP.fromJson(Map<String, dynamic> json) => _$OTPFromJson(json);
  Map<String, dynamic> toJson() => _$OTPToJson(this);
}

方案2:给字段添加JsonKey转换函数

直接在countryID字段上通过JsonKey指定序列化和反序列化函数:

@JsonSerializable()
class OTP {
  @JsonKey(
    fromJson: _unsignedIntFromJson,
    toJson: _unsignedIntToJson
  )
  UnsignedInt? countryID;
  String? phoneNo;

  OTP({this.countryID, this.phoneNo});

  factory OTP.fromJson(Map<String, dynamic> json) => _$OTPFromJson(json);
  Map<String, dynamic> toJson() => _$OTPToJson(this);
}

// 辅助转换函数
UnsignedInt? _unsignedIntFromJson(dynamic json) {
  if (json is int) {
    return UnsignedInt.fromInt(json);
  }
  return null;
}

dynamic _unsignedIntToJson(UnsignedInt? value) {
  return value?.toInt();
}

简化方案

如果服务器仅接收普通整数类型,可直接将模型中的UnsignedInt? countryID替换为int? countryID,无需额外编写转换逻辑,直接适配json_serializable的默认支持类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:51:21