简体   繁体   中英

How to parse json when an attribute might have two types in dart

I am using same model to parse 2 json responses,

In one response an attribute user is string type, and in the other response user is an 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. How should I sort it out? Do I need to create a new model for this single attribute?

You can use is operator in Dart

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM