4

假设有两个模型UserCity

@JsonSerializable()
class User {
    int id;
    String name;
    City? city;
    List<Map<String, City>>? listMapCity;

}

@JsonSerializable()
class City {
   int id;
   String name;
}

现在假设在 API 调用期间,我们有一个用户模型,但在城市对象模型中,我们只得到id而不是name。像这样的东西

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}

但是由于 json_serializable 和 json_annotation 的默认性质。此 JSON 未映射到 User 模型,在映射期间,它会引发异常。
Null 类型不是 String 类型的子类型。(因为这里的城市对象中缺少名称键)

但正如我们已经在 User 对象中声明 City 是可选的,我希望它应该解析带有city的 User JSON,并且listMapCity为空。

任何帮助或解决方案将不胜感激,谢谢

4

1 回答 1

1

您需要在 JsonSerializableUser类上有一个默认构造函数。然后,如果name应该是可空的,则用可空声明它String? name;

这是更新后的 User 类。

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  int id;
  String name;
  City? city;
  List<Map<String, City>>? listMapCity;

  User({required this.id, required this.name, this.city, this.listMapCity});

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  Map<String, dynamic> toJson() => _$UserToJson(this);
}

@JsonSerializable()
class City {
  int id;
  String name;
  City({required this.id, required this.name});
}
于 2021-11-17T04:09:41.723 回答