Flutter:如何将列表转换为JSON

问题描述 投票:0回答:2

我正在尝试将列表转换为Json并将此json发送到DB。

我的列表如下

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});
}

有人可以帮我吗?预先感谢。

json list flutter
2个回答
0
投票

将帮助从JSON进行编码和解码的选项对:json_serializable包是一种为您生成样板化序列化/反序列化代码的好方法。在built_value中有如何使用它的示例(和Flutter samples repo,功能强大,但使用起来更复杂)。


0
投票
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}");

这是我记得的最短的方法。

© www.soinside.com 2019 - 2024. All rights reserved.