【问题标题】:flutter http post "type 'int' is not a subtype of type 'String' in type cast"颤振http帖子“类型'int'不是类型转换中'String'类型的子类型”
【发布时间】:2019-10-12 20:32:47
【问题描述】:

我正在尝试将一些数据发布到此结构的后端:

class Activity {
  String id;
  String employeeId;
  String locationId;
  String locationName;
  DateTime startDateTime;
  DateTime endDateTime;
  int breakMinutes;
  String actionId;
  String actionType;
  int startDeviceType;
  int endDeviceType;
  String comment;

  factory Activity.fromJson(Map<String, dynamic> json) =>
      _$ActivityFromJson(json);
  Map<String, dynamic> toJson() => _$ActivityToJson(this);
}

我正在将类转换为这样的地图:

Map<String, dynamic> _$ActivityToJson(Activity instance) => <String, dynamic>{
      'id': instance.id,
      'employeeId': instance.employeeId,
      'locationId': instance.locationId,
      'locationName': instance.locationName,
      'startDateTime': instance.startDateTime?.toIso8601String(),
      'endDateTime': instance.endDateTime?.toIso8601String(),
      'breakMinutes': instance.breakMinutes,
      'actionId': instance.actionId,
      'actionType': instance.actionType,
      'startDeviceType': instance.startDeviceType,
      'endDeviceType': instance.endDeviceType,
      'comment': instance.comment,
    };

...并使用以下行发送:

Future<HttpError> updateAsync(Activity activity) async {
    var url = '...';

...

    var body = activity.toJson();

    Response response = await http.post(
        url,
        headers: headers,
        body: body,
      );

    if (isSuccess(response.statusCode)) {
      return null;
    }

    return new HttpError(
        errorCode: response.statusCode, errorMessage: response.reasonPhrase);
  }


...那么后端想要接收那些数据:

{
  "startDateTime": "2019-10-12T19:59:22.801Z",
  "endDateTime": "2019-10-12T19:59:22.801Z",
  "breakMinutes": 0,
  "actionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "startDeviceType": 0,
  "endDeviceType": 0,
  "comment": "string"
}

我现在面临的问题是调用 post() 时出错

type 'int' is not a subtype of type 'String' in type cast

如果我在转换为 Map 时对整数值调用 .toString(),我会得到 415 - Unsupported Media Type

这是一个错误还是我真的在这里做错了什么?

【问题讨论】:

  • 这不是一个错误,只是你的后端数据支持string 数据,而你将int 传递给它。转换后发送到后端就可以了。
  • 后端想要接收整数,将命名值转换为字符串我会收到另一个错误,告诉我值无效,所以是的,整数是我要发送的类型跨度>
  • 请显示您将Map&lt;String, dynamic&gt; 转换为 JSON 字符串的代码。出于调试目的,还要检查 body 是否为 String 并打印出来。
  • 我添加了更多代码行。也许他们有助于找到问题

标签: rest http post flutter dart


【解决方案1】:

改变

  var body = activity.toJson(); // here body is still a Map<String, dynamic>

  var body = json.encode(activity.toJson()); // here it's a JSON encoded string

【讨论】:

  • 使用这种方法我得到一个 415 - “不支持的媒体类型”
  • 至少您现在可以访问服务器了。你的标题是什么?
  • 标题无关紧要,因为它们实际上没有被读取。但是我可以通过其他 http 帖子访问服务器,所以这不是问题,这里唯一的问题是 int 值
  • 我对此表示怀疑,因为 int 现在将被正确地 JSON 编码,您可以通过将 body 打印到控制台来证明这一点。你能用 Postman 模拟同样的帖子吗?您是否包含内容类型标头?
  • 在我的标题中添加 "Content-Type" : "application/json" 解决了这个问题,谢谢!
猜你喜欢
  • 2019-08-14
  • 2021-02-25
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 2020-09-29
  • 2020-08-11
  • 1970-01-01
相关资源
最近更新 更多