Deserialize json array in Dart/Flutter

9,036

Solution 1

final List t = json.decode(response.body);
final List<PortasAbertas> portasAbertasList =
     t.map((item) => PortasAbertas.fromJson(item)).toList();
return portasAbertasList;

You can parse your JSON to list like that so you can use fromJson in an array.

Solution 2

You can try using this lines,

List oo = jsonDecode('[{"i":737,"n":1},{"i":222,"n":111}]');
//here u get the values from the first value on the json array
print(oo[0]["i"]);
print(oo[0]["n"]);

//here u get the values from the second value on the json array
print(oo[1]["i"]);
print(oo[1]["n"]);

and for each value from your list, u have a json and can get access the value using "i" or "n";

Share:
9,036
Jackson Felipe Magnabosco
Author by

Jackson Felipe Magnabosco

Python Developer, Java / Java EE / Javascript, C, C #, C ++, Lazarus / Delphi, Database (SQL), Android / iOS application creation in Kotlin and Flutter, C development for Arduino. Concepts about RESTful APIs, as well as documenting, creating and consuming RESTful APIs in any programming language. Use of the Swagger and OpenAPI 3.0 framework to document an API. Creation of unit tests battery, isolation of external dependency test method, being able to define its behavior and validate the interactions carried out, applying the basic TDD method, obtaining quality metrics from the tests (Percentage of acceptance and code coverage). Using JUnit, Mockito, PowerMock, EclEmma (JACOCO), DataBuilders with Fluent Interface and ObjectMother and TDD (Test Driven Development) concepts.

Updated on November 28, 2022

Comments

  • Jackson Felipe Magnabosco
    Jackson Felipe Magnabosco over 1 year

    How to deserialize this json array [{"i":737,"n":1}] to get the variable "i" e "n".

    Class 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
        };
      }
    }
    

    I'm trying deserialize the object using this code, but use it when dont have a array, but using array i don't know i can do it

       PortasAbertas objeto = new PortasAbertas.fromJson(responseJson);
         String _msg = ("Portas abertas: ${objeto.n}");