1

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?

Alvin John Babu
  • 1,710
  • 2
  • 16
  • 26

2 Answers2

3
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.

jsdaniell
  • 390
  • 2
  • 5
  • 12
1

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.

Matt S.
  • 9,902
  • 6
  • 29
  • 25