I have got class that have toJson
method.
class SearchFormModel {
List<String>? purchaseNumbersList;
List<String>? regionsSelectedNames;
SearchFormModel( {
this.purchaseNumbersList,
this.regionsSelectedNames
}
);
Map toJson() => {
'purchaseNumbersList': purchaseNumbersList,
'regionsNames': regionsSelectedNames
};
}
I want to prevent adding fields with null
values to Json.
For example if purchaseNumbersList
is null
it should not be added to result JSON.
How to do it in Dart?
You can use collection if to optionally include a key/value pair in a map literal.
class SearchFormModel {
List<String>? purchaseNumbersList;
List<String>? regionsSelectedNames;
SearchFormModel({
this.purchaseNumbersList,
this.regionsSelectedNames
});
Map toJson() => {
if (purchaseNumbersList != null) 'purchaseNumbersList': purchaseNumbersList,
if (regionsSelectedNames != null) 'regionsNames': regionsSelectedNames,
};
}
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.