Dart如何正确序列化包含整数列表的DTO?
正确序列化含整数列表DTO的方法
你遇到的问题根源是直接将Map作为POST请求体传递时,未完成正确的JSON序列化,导致整数列表mIds被错误按字符串类型处理。
解决步骤如下:
- 导入必要依赖:确保项目中导入
dart:convert库,它提供JSON序列化工具。 - 将Map转为JSON字符串:不要直接把
toMap()返回的Map作为请求体,用json.encode()将其转换为JSON格式字符串。 - 设置请求头:发送请求时指定
Content-Type为application/json,告知服务器请求体为JSON格式。
示例代码:
import 'dart:convert'; import 'package:http/http.dart' as http; // 你的DTO类 class YourDto { final String languageCode; final List<int> mIds; YourDto({required this.languageCode, required this.mIds}); Map<String, dynamic> toMap() => { "languageCode": languageCode, "mIds": mIds, }; } // 发送POST请求的示例 Future<void> sendDto(YourDto dto) async { final url = Uri.parse('你的接口地址'); final headers = {'Content-Type': 'application/json'}; final jsonBody = json.encode(dto.toMap()); // 关键:将Map转为JSON字符串 final response = await http.post( url, headers: headers, body: jsonBody, ); // 后续处理响应... }
也可以用json_serializable包自动生成序列化代码,避免手动编写toMap()的潜在错误:
- 在
pubspec.yaml添加json_annotation、json_serializable、build_runner依赖 - 给DTO类添加注解,运行构建命令生成序列化代码
示例(使用json_serializable):
import 'package:json_annotation/json_annotation.dart'; part 'your_dto.g.dart'; @JsonSerializable() class YourDto { final String languageCode; final List<int> mIds; YourDto({required this.languageCode, required this.mIds}); factory YourDto.fromJson(Map<String, dynamic> json) => _$YourDtoFromJson(json); Map<String, dynamic> toJson() => _$YourDtoToJson(this); // 自动生成的序列化方法 }
运行dart pub run build_runner build生成对应的.g.dart文件,发送请求时直接用json.encode(dto.toJson())即可。
内容的提问来源于stack exchange,提问作者Jaczura Zoltán
相关产品推荐
相关产品推荐

