Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Pegar dados de uma API

Opa, boa tarde,

como faco para acessar mais de um nivel do meu JSON,

por exemplo ..eu tenho o JSON.

resultado do JSON
[
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "Sincere@april.biz",
        "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
                "lat": "-37.3159",
                "lng": "81.1496"
            }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        }
    },
    ...
webclient.dar

Future<List<Pessoa>> findAll() async {
  http.Client client =
      InterceptedClient.build(interceptors: [LoggingInterceptor()]);

  final http.Response response = await client
      .get(Uri.parse('https://jsonplaceholder.typicode.com/users'))
      .timeout(const Duration(seconds: 55));

  // print('AQUIIII:  ${response.body}');

  // final List<dynamic> decodedJson = jsonDecode(response.body);

  final List<dynamic> decodedJson = json.decode(response.body);

  final List<Pessoa> pessoas = [];

  for (Map<String, dynamic> pessoaJson in decodedJson) {
    final Map<String, dynamic> EnderecoJson = pessoaJson['address'];
    final Map<String, dynamic> CompanyJson = pessoaJson['company'];
    final Map<String, dynamic> GeoJson = pessoaJson['address']['geo'];  // CREIO QUE O PROBLEMA ESTEVA AQUI :(

    final Pessoa pessoa = Pessoa(
      pessoaJson['id'],
      pessoaJson['name'],
      pessoaJson['username'],
      pessoaJson['email'],
      Enderaco(
        EnderecoJson['street'],
        EnderecoJson['suite'],
        EnderecoJson['city'],
        EnderecoJson['zipcode'],
      ),
      Geo(
      GeoJson['lat'],
      GeoJson['lnt'],
      ),
      pessoaJson['phone'],
      pessoaJson['website'],
      Company(
        CompanyJson['name'],
        CompanyJson['catchPhrase'],
        CompanyJson['bs'],
      ),
    );
    pessoas.add(pessoa);
  }
  return pessoas;
}



MODELS
import 'package:api/models/company.dart';
import 'package:api/models/enderaco.dart';
import 'package:api/models/geo.dart';

class Pessoa {
  final int id;
  final String name;
  final String username;
  final String email;
  final Enderaco enderaco;
  final Geo geo;
  final String phone;
  final String website;
  final Company company;

  Pessoa(
    this.id,
    this.name,
    this.username,
    this.email,
    this.enderaco,
    this.geo,
    this.phone,
    this.website,
    this.company,
  );
}




class Enderaco {
  final String street;
  final String suite;
  final String city;
  final String zipcode;

  Enderaco(
    this.street,
    this.suite,
    this.city,
    this.zipcode,
  );
}




class Geo {
  final String lat;
  final String lng;

  Geo(
    this.lat,
    this.lng,
  );
}

O problema todo eh que eu nao consigo puxar os dados quando o JSON esta encadeado. por exemplo eu consigo acessar normalmente os dados de street que esta dentro de address, porem nao consigo acessar geo que esta dentro de address.

1 resposta
solução!

Consegui resolver Utilizando o site https://javiercbk.github.io/json_to_dart/

model

class Api {
  int? id;
  String? name;
  String? username;
  String? email;
  Address? address;
  String? phone;
  String? website;
  Company? company;

  Api({
    required this.id,
    required this.name,
    required this.username,
    required this.email,
    required this.address,
    required this.phone,
    required this.website,
    required this.company,
  });

  Api.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    username = json['username'];
    email = json['email'];
    address =
        json['address'] != null ? new Address.fromJson(json['address']) : null;
    phone = json['phone'];
    website = json['website'];
    company =
        json['company'] != null ? new Company.fromJson(json['company']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['username'] = this.username;
    data['email'] = this.email;
    if (this.address != null) {
      data['address'] = this.address!.toJson();
    }
    data['phone'] = this.phone;
    data['website'] = this.website;
    if (this.company != null) {
      data['company'] = this.company!.toJson();
    }
    return data;
  }
}

class Address {
  String? street;
  String? suite;
  String? city;
  String? zipcode;
  Geo? geo;

  Address({
    required this.street,
    required this.suite,
    required this.city,
    required this.zipcode,
    required this.geo,
  });

  Address.fromJson(Map<String, dynamic> json) {
    street = json['street'];
    suite = json['suite'];
    city = json['city'];
    zipcode = json['zipcode'];
    geo = json['geo'] != null ? new Geo.fromJson(json['geo']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['street'] = this.street;
    data['suite'] = this.suite;
    data['city'] = this.city;
    data['zipcode'] = this.zipcode;
    if (this.geo != null) {
      data['geo'] = this.geo!.toJson();
    }
    return data;
  }
}

class Geo {
  String? lat;
  String? lng;

  Geo({
    required this.lat,
    required this.lng,
  });

  Geo.fromJson(Map<String, dynamic> json) {
    lat = json['lat'];
    lng = json['lng'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['lat'] = this.lat;
    data['lng'] = this.lng;
    return data;
  }
}

class Company {
  String? name;
  String? catchPhrase;
  String? bs;

  Company({
    required this.name,
    required this.catchPhrase,
    required this.bs,
  });

  Company.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    catchPhrase = json['catchPhrase'];
    bs = json['bs'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['catchPhrase'] = this.catchPhrase;
    data['bs'] = this.bs;
    return data;
  }
}

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software