Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a class into JSON or List

Tags:

flutter

dart

How to convert this class into JSON or List?

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

Edit

I'm changed my class and works fine to my case:

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

Then I use:

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

sqlite.rowInsert("insert into client(id, name)", client.fields.Keys.toList(), client.fields.Values.toList());
like image 585
Matheus Miranda Avatar asked Aug 13 '18 01:08

Matheus Miranda


People also ask

How do you convert a class to a JSON object in Python?

Conversion of the class object to JSON is done using json package in Python. json. dumps() converts Python object into a json string. Every Python object has an attribute which is denoted by __dict__ and this stores the object's attributes.

Can you convert list to JSON?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

Which class is used to convert an object or value to or from JSON?

The ObjectMapper class of the Jackson API in Java provides methods to convert a Java object to JSON object and vice versa.

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.


1 Answers

Just create a method inside your class and return a 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,
        };
  }

And use it for example :

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

Also you can try using this package to avoid writing all of your fields : https://pub.dartlang.org/packages/json_serializable

like image 141
diegoveloper Avatar answered Oct 18 '22 20:10

diegoveloper