简体   繁体   中英

Flutter: How to convert a List to JSON

I am trying to convert a list to Json and sent this json to DB.

My list is as following

List<DeviceInfo> deviceInfoList = [];

class DeviceInfo {
  final String platform;
  final String deviceModel;
  final bool isPhysicalDevice;
  final String deviceId;
  final String imei;
  final String meid;
  final String platformVersion;
  final String projectVersion;
  final String projectCode;
  final String projectAppID;
  final String projectName;

  DeviceInfo(
      {this.platform,
      this.platformVersion,
      this.deviceModel,
      this.isPhysicalDevice,
      this.deviceId,
      this.imei,
      this.meid,
      this.projectVersion,
      this.projectCode,
      this.projectAppID,
      this.projectName});
}

My list contain String and boolean, I had go through this example don't know how to Map string and bool in that map function. Can anyone help me with this?

Couple of options that will help encoding and decoding from JSON: the json_serializable package is a great way to have the boilerplate serialize/deserialize code generated for you. There's examples of how to use this (and built_value , which is powerful, but more complicated to use) in the Flutter samples repo .

Map<String,dynamic> toJson(){
    return {
      "name": this.name,
      "number": this.number,
      "surname": this.surname,
    };
  }

static List encondeToJson(List<DeviceInfo>list){
    List jsonList = List();
    list.map((item)=>
      jsonList.add(item.toJson())
    ).toList();
    return jsonList;
}

List jsonList = Device.encondeToJson(deviceInfoList);
print("jsonList: ${jsonList}");

Is the most short way that I remember.

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.

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