![](/img/trans.png)
[英]Flutter: Issue while converting json to model using json_serializable
[英]Flutter: how to apply defaultValue when I create a model with null value when using json_serializable?
@JsonSerializable()
class TestModelA {
@JsonKey(defaultValue: 'jp')
final String? language;
@JsonKey(defaultValue: 'jp')
final String? location;
TestModelA(this.language, this.location);
factory TestModelA.fromJson(Map<String, dynamic> json) =>
_$TestModelAFromJson(json);
Map<String, dynamic> toJson() => _$TestModelAToJson(this);
}
我有這個帶有@JsonKey
defaultValue 的JsonSerializable()
。 如何分配該默認值?
當我使用 null 值創建 model 時,它只使用 null 值進行設置。 如何通過分配 defaultValues 創建 TestModelA?
試試下面的代碼。 JSON 如果 null 然后使用構造函數傳遞值
factory TestModelA.fromJson(Map<String, dynamic> json) =>
json!=null? _$TestModelAFromJson(json): TestModelA("English","US");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.