25

I have a list of option when the attribute is selected of a particular option then I save attribute object at the selected position of option in the list. now I have an option list with their selected attribute object. My aim is to convert the options list into JSON object but when the attribute is not null. The Attribute object can be null in that case when a person has not chosen an attribute of an option.

class OptionAttribute{
 String _grouprowid;
 String _groupname;
 Attribute _selectedAttrObject

   Map<String, dynamic> toJson() => {
    'attribute': _selectedAttrObject,
  };
}

class Attribute{

  String _attributerowid;
  String _grouprowid;
  String _attributename;
  String _weight;

   Map<String, dynamic> toJsonAttr() => {
    'attrid': _attributerowid,
    'groupid': _grouprowid,
    'attrname': _attributename
  };

}

I want to convert below list into JSON object when the list does not have any null attribute.

List<OptionAttribute> opAtrrList=new List<OptionAttribute>();
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105

1 Answers1

59

You need to convert each item individually

var json = jsonEncode(opAttrList.map((e) => e.toJson()).toList());

or pass an toEncodable function

var json = jsonEncode(opAttrList, toEncodable: (e) => e.toJsonAttr());
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567