dart - 将类转换为 JSON 或 List

如何将这个类转换成 JSON 或 List?

class cliente {
  int id;
  String nome;
  String apelido;
  String sexo;
  String status;
}

编辑

我换了类,我的情况很好:

class client {
  Map<String, dynamic> fields => {
  "id": "",
  "name": "",
  "nickname": "",
  "sex": "",
  "status": "",
}

然后我使用:

client.fields["id"]   = 1;
client.fields["name"] = "matheus";

sqlite.rowInsert("insert into client(id, name)", client.fields.Keys.toList(), client.fields.Values.toList());

最佳答案

只需在您的类中创建一个方法并返回 Map<String, dynamic>

  class cliente {
    int id;
    String nome;
    String apelido;
    String sexo;
    String status;

    Map<String, dynamic> toJson() => {
          'id': id,
          'nome': nome,
          'apelido': apelido,
          'sexo': sexo,
          'status': status,
        };
  }

并以它为例:

final dataObject = new client(); 
...fill your object
final jsonData = dataObject.toJson();  

您也可以尝试使用此包来避免写入所有字段:https://pub.dartlang.org/packages/json_serializable

https://stackoverflow.com/questions/51814063/

相关文章:

dart - 如何使用 flutter 在移动应用程序中禁用多点触控

android - 如何使用 Flutter 将图像上传到 Firebase

dart - flutter 中的下拉按钮不会将值切换到所选值

dart - 回复 : create a dropdown button in flutter

firebase - 无法为 flutter 构建发布 APK

dart - 底部带有滚动页脚的 ListView

dart - Flutter:将盒子阴影添加到透明容器

dart - 在小部件树中使用 const 会提高性能吗?

dart - Flutter Http错误SocketException : OS Error: C

flutter - 具有水平、未填充子项的 PageView