Flutter中如何将数据类转为JSON发送至后端?
解决Dart注册请求中Profile字段序列化不匹配问题
有三种可行的解决思路,根据你的实际场景选择:
1. 修改Profile类的toJson方法(最直接)
既然不能修改类内的字段名,直接在toJson方法里把字段映射成后端要求的下划线命名键就行,这是序列化的标准做法:
class Profile { final String countryIsoCode; Profile({required this.countryIsoCode}); // 修改后的toJson方法 Map<String, dynamic> toJson() { return { 'country_iso_code': countryIsoCode, }; } }
这样jsonEncode(data)时,Profile实例会被序列化为{"country_iso_code": "xxx"},后端就能同时识别profile参数和正确的字段。
2. 手动构造profile的Map(无需修改Profile类)
如果没法改动Profile类的代码,就在构造请求数据时,手动把Profile的字段转成符合要求的Map结构:
// 先创建Profile实例 final profile = Profile(countryIsoCode: country); Map data = { 'username': name, 'email': email, 'password1': password1, 'password2': password2, 'profile': { 'country_iso_code': profile.countryIsoCode, }, };
这种方式绕开了Profile自身的序列化逻辑,直接给后端返回期望的结构。
3. 用json_serializable的注解(适合代码生成场景)
如果你的项目用json_serializable包做序列化,可以给Profile的字段加@JsonKey注解指定序列化后的键名:
import 'package:json_annotation/json_annotation.dart'; part 'profile.g.dart'; @JsonSerializable() class Profile { @JsonKey(name: 'country_iso_code') final String countryIsoCode; Profile({required this.countryIsoCode}); factory Profile.fromJson(Map<String, dynamic> json) => _$ProfileFromJson(json); Map<String, dynamic> toJson() => _$ProfileToJson(this); }
运行代码生成命令后,自动生成的toJson方法会自动把countryIsoCode映射为country_iso_code,完美适配后端要求。
内容的提问来源于stack exchange,提问作者Robban13
相关产品推荐
相关产品推荐

