简体   繁体   English

转换清单 <T> 扑入json

[英]Convert List<T> into json in flutter

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. 我的目的是将选项列表转换为JSON对象,但是当属性不为null时。 The Attribute object can be null in that case when a person has not chosen an attribute of an option. 在这种情况下,如果人们没有选择选项的属性,则Attribute对象可以为null。

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. 当列表没有任何null属性时,我想将以下列表转换为JSON对象。

List<OptionAttribute> opAtrrList=new List<OptionAttribute>();

You need to convert each item individually 您需要单独转换每个项目

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

or pass an toEncodable function 或传递toEncodable函数

var json = jsonEncode(opAttrList, toEncodable: (e) => e.toJsonAttr());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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