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
– Matheus Ribeiro