Home > Blockchain >  How can I map items from json with http get method flutter?
How can I map items from json with http get method flutter?

Time:08-13

I`m trying to use an http get method in flutter, but my json is returned like this:

{"items":[{"id":1,"nome":"Ricardo","telefone":"(14) 99797-5621"}],"hasMore":false,"limit":25,"offset":0,"count":1,"links":[{"rel":"self","href":"http://172.16.30.120:8080/ords/apiteste/integrafoods/users"},{"rel":"describedby","href":"http://172.16.30.120:8080/ords/apiteste/metadata-catalog/integrafoods/item"},{"rel":"first","href":"http://172.16.30.120:8080/ords/apiteste/integrafoods/users"}]}

And i`m trying to retrieve info this way:

Future<void> _loadUsers() async {
    final response = await http.get(
      Uri.parse(_url),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );
    if (response.body == 'null') return;
    Map<String, dynamic> data = jsonDecode(response.body);
    data.forEach(
      (items, userData) {
        teste.add(
          AppUser(
            id: items,
            login: userData['login'],
            phoneNumber: userData['telefone'],
          ),
        );
      },
    );
    print(_teste.length);
  }

But it's not working, it throws error: "[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'".

But if i use code this way, it returns all parameters from the json:

Future<void> _loadUsers() async {
    final response = await http.get(
      Uri.parse('http://172.16.30.120:8080/ords/apiteste/integrafoods/users'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
    );
    if (response.body == 'null') return;
    Map<String, dynamic> data = jsonDecode(response.body);
    data.forEach(
      (items, userData) {
        teste.add(
          AppUser(
            login: userData['items'].toString(),
          ),
        );
      },
    );
    print(_teste.length);
  }

How can i map this "items" json so i get each parameter separetadely?

class AppUser {
  // final String CPF;
  final String id;
  final String? login;
  final String? name;
  final String? email;
  final String? situation;
  final String? phoneNumber;
  final String? password;
  final String? inclusionDt;
  final String? inclusionUs;
  final String? altDt;
  final String? altUs;
  final String company;

  const AppUser({
    // required this.CPF,
    required this.id,
    this.login,
    this.name,
    this.email,
    this.situation,
    this.phoneNumber,
    this.password,
    this.inclusionDt,
    this.inclusionUs,
    this.altDt,
    this.altUs,
    this.company = 'GTFoods',
  });
}

CodePudding user response:

You can use this model class

import 'dart:convert';

class MyItem {
  final int id;
  final String? nome;
  final String? telefone;
  MyItem({
    required this.id,
    required this.nome,
    required this.telefone,
  });

  Map<String, dynamic> toMap() {
    final result = <String, dynamic>{};

    result.addAll({'id': id});
    if (nome != null) {
      result.addAll({'nome': nome});
    }
    if (telefone != null) {
      result.addAll({'telefone': telefone});
    }

    return result;
  }

  factory MyItem.fromMap(Map<String, dynamic> map) {
    return MyItem(
      id: int.tryParse(map['id'].toString()) ?? 0,
      nome: map['nome'],
      telefone: map['telefone'],
    );
  }

  String toJson() => json.encode(toMap());

  factory MyItem.fromJson(String source) => MyItem.fromMap(json.decode(source));
}

Try using

final  data = jsonDecode(response.body)['items'] as List?;

if (data  != null) {
    final items = data.map((e) => MyItem.fromJson(e)).toList();
    print(data);
  }

  • Related