Home > Enterprise >  How to prevent serialization to Json null values?
How to prevent serialization to Json null values?

Time:06-22

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?

CodePudding user response:

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,
  };
}
  • Related