[英]How to parse json when an attribute might have two types in dart
I am using same model to parse 2 json responses,我正在使用相同的 model 来解析 2 个 json 响应,
In one response an attribute user
is string type, and in the other response user
is an object.在一个响应中,属性
user
是字符串类型,而在另一个响应中, user
是 object。
How could I parse in this situation?在这种情况下我该如何解析? I tried,
我试过了,
CampaignProductDetails.fromJson(Map<String, dynamic> json) {
user= json['user'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['user'] = this.user;
return data;
}
But it shows _typeError when user
is an object.但是当
user
是 object 时,它会显示 _typeError。 How should I sort it out?我该如何整理? Do I need to create a new model for this single attribute?
我需要为这个单一属性创建一个新的 model 吗?
You can use is
operator in Dart您可以在 Dart 中使用
is
运算符
CampaignProductDetails.fromJson(Map<String, dynamic> json) {
user= json['user'] == null ? null : (json['user'] is String ? json['user'] : this.user;
}
as an alternative, In Dart every object has a runtimeType
instance member which returns type of object at runtime ( I wouldn't advice to use it on production, somewhere read that it is only for debugging purpose).作为替代方案,在 Dart 中,每个 object 都有一个
runtimeType
实例成员,它在运行时返回 object 的类型(我不建议在生产中使用它,在某处读到它只是)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.