使用@jsonserializable()时,如何在飞镖/颤动中具有动态多元值?
我正在使用json_annotation
库的扑朔迷离,并且有一个用于表示来自一个API的JSON响应的数据类。
import 'package:json_annotation/json_annotation.dart';
import 'package:app/dtos/user.dart';
import 'package:app/dtos/limited_user.dart';
part 'pending_project.g.dart';
@JsonSerializable()
class PendingProject {
@JsonKey(name: "user")
final User|LimitedUser user; // here I might have sometimes returned User type other types LimitedUser
@JsonKey(name: "updatedAt")
final String updatedAt;
PendingProject(this.user, this.updatedAt);
factory PendingProject.fromJson(Map<String, dynamic> json) =>
_$PendingProjectFromJson(json);
Map<String, dynamic> toJson() => _$PendingProjectToJson(this);
}
API基于某些逻辑返回用户
字段的不同值。 Sometimes objects of type User
other types of type LimitedUser
I have both those objects defined but cannot make it work in the json schema above.
How can I leave user object as dynamic maybe or json string and further parse manually in code or some other solution
Both User
and LimitedUser
have one common field named type< /代码>,这使我们能够区分回来的东西。
for User, type="user"
for LimitedUser, type="limitedUser"
all the other fields can be different we cannot assume anything else
PS: pending_project.g.dart是通过运行flutter packages pub run build build_runner构建
的自动生成的文件
I am using Flutter with json_annotation
library and have one data class that is used to represent json response coming from one api.
import 'package:json_annotation/json_annotation.dart';
import 'package:app/dtos/user.dart';
import 'package:app/dtos/limited_user.dart';
part 'pending_project.g.dart';
@JsonSerializable()
class PendingProject {
@JsonKey(name: "user")
final User|LimitedUser user; // here I might have sometimes returned User type other types LimitedUser
@JsonKey(name: "updatedAt")
final String updatedAt;
PendingProject(this.user, this.updatedAt);
factory PendingProject.fromJson(Map<String, dynamic> json) =>
_$PendingProjectFromJson(json);
Map<String, dynamic> toJson() => _$PendingProjectToJson(this);
}
The api returns different values for user
field based on some logic.
Sometimes objects of type User
other types of type LimitedUser
I have both those objects defined but cannot make it work in the json schema above.
How can I leave user object as dynamic maybe or json string and further parse manually in code or some other solution
Both User
and LimitedUser
have one common field named type
that allows us to differentiate what we got back.
for User, type="user"
for LimitedUser, type="limitedUser"
all the other fields can be different we cannot assume anything else
PS:
pending_project.g.dart is auto generated file with the library itself by running flutter packages pub run build_runner build
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
continue
I solved this by using
fromJson
as belowThe other code in ui is checking: