问题描述
假设有两个模型User和City
@JsonSerializable()
class User {
int id;
String name;
City? city;
}
@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 类型的子类型。 (因为这里 name 键在 city 对象中丢失)
但是因为我们已经在 User 对象中声明 City 是可选的,我希望它应该解析 User JSON 中的 city 为 null。
非常感谢任何帮助或解决方案,谢谢
解决方法
目前不支持仅在序列化或仅在反序列化时忽略某个字段。您可以忽略两者或都不忽略。但是,我使用了一种解决方法。
- 在您的模型文件中创建一个只返回 null 的全局方法,如下所示:
T? toNull<T>(_) => null;
- 在您的
User
模型中为 City 添加自定义JsonKey
:
@JsonKey(fromJson: toNull,includeIfNull: false)
City? City;
这样做是在从 Json 转换时,它使用您指定的函数来转换 city
并用 null 替换您的值。然后由于 includeIfNull
属性,它只是跳过解析。