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>();
jsonEncode function Null safetyConverts object to a JSON string. If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.
In Dart, a list is an indexable collection of objects with a length while a set is a collection of objects where each object can occur only once. This short article shows you how to convert a list to a set and vice versa, turn a set into a list. The toSet() method helps us do the job.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With