0

我有一个问题,我有一个简单的模型类,它的变量很少,但是其中一个不一定总是存在。但是如果 json 数据中没有该键,则 JsonSerializable 不会将 json 转换为模型对象。

示例代码 -

import "package:json_annotation/json_annotation.dart";

part "address.g.dart";

@JsonSerializable()
class Address {
  final String country_code, state, city, street_line1, street_line2, post_code;

  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);
}

如您所见,它是一个模型类,但 street_line2 并不总是存在。如果它不存在,则 json 可序列化不起作用。

4

1 回答 1

1

利用 ”?” 对于模型中的可为空变量

像这样:字符串?那么它可以为空

于 2021-09-08T10:00:07.037 回答