json_serializable遇JSON缺少Model类声明字段无法转换如何处理
问题原因
Dart空安全机制下,你当前声明的street_line2为非空String类型,json_serializable默认要求JSON中必须存在对应key且值不为null,否则会抛出解析失败异常。
解决方案
你可以根据业务需求选择以下任意一种方案:
方案1:将可选字段声明为可空类型
适合允许该字段值为null的业务场景,修改后的代码如下:
import "package:json_annotation/json_annotation.dart"; part "address.g.dart"; @JsonSerializable() class Address { final String country_code, state, city, street_line1, post_code; // 声明为可空类型,表示该字段可能不存在 final String? street_line2; Address(this.country_code, this.state, this.city, this.street_line1, this.street_line2, this.post_code); factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json); Map<String, dynamic> toJson() => _$AddressToJson(this); }
修改后如果JSON中缺少street_line2字段,解析后该字段值为null,不会触发异常。
方案2:给字段设置默认值
适合字段缺省时需要取固定默认值的业务场景,不需要修改字段可空属性,修改方式如下:
import "package:json_annotation/json_annotation.dart"; part "address.g.dart"; @JsonSerializable() class Address { final String country_code, state, city, street_line1, post_code; // 通过JsonKey注解指定默认值为空字符串 @JsonKey(defaultValue: '') final String street_line2; Address(this.country_code, this.state, this.city, this.street_line1, this.street_line2, this.post_code); factory Address.fromJson(Map<String, dynamic> json) => _$AddressFromJson(json); Map<String, dynamic> toJson() => _$AddressToJson(this); }
你也可以直接在构造函数参数中指定默认值,效果完全一致:
Address(this.country_code, this.state, this.city, this.street_line1, [this.street_line2 = '', this.post_code]);
生效操作
修改完Model类代码后,需要重新执行构建命令生成新的解析代码:
- Flutter项目执行:
flutter pub run build_runner build - 纯Dart项目执行:
dart run build_runner build
内容的提问来源于stack exchange,提问作者user16859477
相关产品推荐
相关产品推荐

