小编Him*_*ora的帖子

Flutter:json_serialized 忽略可为 null 的字段而不是抛出错误

假设有两个模型UserCity

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

}

@JsonSerializable()
class City {
   int id;
   String name;
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}
Run Code Online (Sandbox Code Playgroud)

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

但正如我们已经在 User 对象中声明的 City 是可选的,我希望它应该解析 User JSON,其中citylistMapCity为 null。

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

dart flutter json-serializable dart-null-safety

11
推荐指数
2
解决办法
9896
查看次数