将类转换为JSON或列表

时间:2018-08-13 01:06:37

标签: dart flutter

如何将此类转换为JSON或列表?

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

2 个答案:

答案 0 :(得分:7)

只需在您的类中创建一个方法并返回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

答案 1 :(得分:1)

  
    

如何将此类转换为JSON或列表?

  

为此使用代码生成器是正确的解决方案之一,如@diegoveloper答案中所述。
在这种情况下,您的代码可能类似于以下示例。

// Generated by 'yaml2podo'
// Version: 0.1.11
// https://pub.dev/packages/yaml2podo

class Client {
  final String nickname;
  final String status;
  final String name;
  final int id;
  final String sex;

  Client({this.nickname, this.status, this.name, this.id, this.sex});

  factory Client.fromJson(Map map) {
    return Client(
        nickname: map['nickname'] as String,
        status: map['status'] as String,
        name: map['name'] as String,
        id: map['id'] as int,
        sex: map['sex'] as String);
  }

  Map<String, dynamic> toJson() {
    var result = <String, dynamic>{};
    result['nickname'] = nickname;
    result['status'] = status;
    result['name'] = name;
    result['id'] = id;
    result['sex'] = sex;
    return result;
  }
}

/*
Client:
  id: int
  name: String
  nickname: String
  sex: String
  status: String
*/