Deserializar json vector in Dart/Flutter

Asked

Viewed 860 times

0

I’m trying to deserialize this json vector [{"i":737,"n":1}] but I’m not getting the variables "i" and "n".

Class to deserialize

class PortasAbertas {
  int i;
  int n;

  PortasAbertas({this.i, this.n});

  PortasAbertas.fromJson(Map<int, dynamic> json) {
    i = json[i];
    n = json[n];
  }

  Map<int, dynamic> toJson() {
    final Map<int, dynamic> data = new Map<int, dynamic>();
    data[i] = this.i;
    data[n] = this.n;
    return data;
  }
}

Object I’m using to deserialize

 if (endereco == "portasabertas") {
     PortasAbertas objeto = new PortasAbertas.fromJson(responseJson);
      if (objeto.n == "[]"){
        _msg = ("Nenhuma porta esta aberta");
      } else {
        _msg = ("Portas abertas ${objeto.n}");
      }
    }

3 answers

1


Here’s an example of how you can do it

class Service extends Entity{
  int           id;
  int           idUser;
  DateTime      startDate;
  DateTime      endDate;
  String        title;
  String        subtitle;
  String        description;
  double        price;
  int           ranking;

  dynamic toClass(Map<String, dynamic>  data){
    id          = data["id"];
    idUser      = data["iduser"];
    startDate   = DateTime.parse(data["startdate"]);
    endDate     = (data["enddate"]=="null") ? DateTime.parse(data["enddate"]) : null;
    image       = data["image"];
    title       = data["title"];
    subtitle    = data["subtitle"];
    description = data["description"];
    price       = double.parse(data["price"]??0);
    ranking     = 0;

    return this;
  }

  Map<String, dynamic> toJSON(){

    return {
      // "id"          : "$id",
      "idUser"      : "$idUser",    
      "startDate"   : "$startDate",          
      "endDate"     : "$endDate",            
      "image"       : "$image",             
      "title"       : "$title",     
      "subtitle"    : "$subtitle",       
      "description" : "$description",       
      "price"       : "$price",             
      "ranking"     : ranking,
    };
  }  
}

Note: This is an excerpt from a class I use in my project

Explanation

JSON always returns a set of KEY : VALUE where the KEY is always a String, soon for you to fetch the data from a KEY you do as follows

variavel = json["CHAVE"];

This method of yours is somewhat wrong, because the parameter it receives does not match the JSON structure

  PortasAbertas.fromJson(Map<int, dynamic> json) {
    i = json[i];
    n = json[n];
  }

It is right for you to create the parameter as follows

Map<String, dynamic> json

That way it would be right

  PortasAbertas.fromJson(Map<String, dynamic> json) {
    i = json["i"];
    n = json["n"];
  }

Edited

I created this example, see if it fits you, because as you are receiving an array of objects, I believe you can receive data from more than one port...

import 'dart:convert';

/*Aqui é sua classe*/
class PortasAbertas {
  int i;
  int n;

  PortasAbertas({this.i, this.n});

  PortasAbertas fromJson(Map<String, dynamic> json) {
    this.i = json['i'];
    this.n = json['n'];
    return this;
  }

  Map<String, dynamic> toJson() {
    return {
      'i': i,
      'n': n
      };
  }
}

/*Aqui é como você irá utilizar a sua classe*/
void main() {
  var jsonData = '[{"i":737,"n":1}]';
  var parsedJson = json.decode(jsonData);
  
  dynamic portasAbertas = parsedJson.map((value){
    return value;
  }).toList();

  PortasAbertas objeto = PortasAbertas();
  objeto.fromJson(portasAbertas[0]);
  print('I = ${objeto.i}');
  print('N = ${objeto.n}');
}

Note: You can run this example here in this website and see how it works.

Explanation

I took your JSON, broke it into a list of Map<String, dynamic> who will own all of your Jsonarray’s objects. Then I took position 0 from your list and played in your class.

  • That’s right, in my reply I left some other examples too, as for example convert a date to a field of type Datetime

1

Paraphrasing this my article (if you want to read integer contains a full example of json deserialization):

If we stop to analyze, any Json structure is basically a Key/value map, so this is exactly how it is represented in Dart. In line 8 we created the fromJson constructor that we will use to deserialize the json, that is, to transform to an Object, by this it receives a String Map(the key will always be string) and Dynamic, which for Dart is like a generic type, any type may be in a dynamic type variable.

Basically every Map key that represents Json is a String, just as every value is at first a dynamic. You’re treating the key like int, then change to String:

PortasAbertas.fromJson(Map<String, dynamic> json) {
  i = json['i'];
  n = json['n'];
}

The process of 'serialization' works equally, also using String:

Map<String, dynamic> toJson() {
  return {
    'i':i,
    'n':n
  };
}

0

It would be that way then to deserialize ?

class PortasAbertas {
  int i;
  int n;

  PortasAbertas({this.i, this.n});

  PortasAbertas.fromJson(Map<String, dynamic> json) {
    i = json['i'];
    n = json['n'];
  }

  Map<String, dynamic> toJson() {
    return {
      'i': i,
      'n': n
    };
  }
}
  • 1

    That’s right, but just one piece of information, implement this in your question, editing it! It’s not cool for you to answer your question with another question! ...

  • Okay, thanks for the tip

  • Now how do I get the vector ? i was doing so : Number Object = new Number Ports.fromJson(responseJson); _msg = ('Total number of ports: ${object.numbers deportas}'); but to get json without vector, with vector I still don’t know how to do

  • Check the edition of my reply and any questions, use the comments section of my reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.