Home > other >  Store JSON to a Map
Store JSON to a Map

Time:11-04

I have a JSON response that I would like to store in a map but do not seem to understand how to proceed with this. The JSON that I would like to store is:

{
    "results": [
        {
            "gender": "female",
            "name": {
                "title": "Mrs",
                "first": "Claudine",
                "last": "da Mota"
            },
            "location": {
                "street": {
                    "number": 4066,
                    "name": "Beco dos Namorados"
                },
                "city": "Poá",
                "state": "Amapá",
                "country": "Brazil",
                "postcode": 55840,
                "coordinates": {
                    "latitude": "-72.3427",
                    "longitude": "112.5891"
                },
                "timezone": {
                    "offset": "-8:00",
                    "description": "Pacific Time (US & Canada)"
                }
            },
            "email": "[email protected]",
            "login": {
                "uuid": "247261b1-80a5-428a-a906-a381efe93cb7",
                "username": "happyostrich285",
                "password": "2000",
                "salt": "bQwiFMAM",
                "md5": "c60b9d4138e4fb0d76182d3397ab35bd",
                "sha1": "d8e40944ed0d9d95f6c44d3d40f9d9e26e3cc04a",
                "sha256": "71d28bb93f2a386c23591c091c3b2bab2e1af89c3ad6d83af359398eb0637fe3"
            },
            "dob": {
                "date": "1974-08-05T08:07:07.202Z",
                "age": 47
            },
            "registered": {
                "date": "2003-11-08T05:19:12.790Z",
                "age": 18
            },
            "phone": "(98) 5277-4740",
            "cell": "(53) 0832-4652",
            "id": {
                "name": "",
                "value": null
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/women/89.jpg",
                "medium": "https://randomuser.me/api/portraits/med/women/89.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/women/89.jpg"
            },
            "nat": "BR"
        },
        {
            "gender": "male",
            "name": {
                "title": "Mr",
                "first": "Lauri",
                "last": "Autio"
            },
            "location": {
                "street": {
                    "number": 7571,
                    "name": "Tahmelantie"
                },
                "city": "Pälkäne",
                "state": "Lapland",
                "country": "Finland",
                "postcode": 58979,
                "coordinates": {
                    "latitude": "40.0496",
                    "longitude": "-34.1528"
                },
                "timezone": {
                    "offset": "-12:00",
                    "description": "Eniwetok, Kwajalein"
                }
            },
            "email": "[email protected]",
            "login": {
                "uuid": "1850e546-a847-4770-8cdb-48903c2874d1",
                "username": "beautifulleopard611",
                "password": "stinger",
                "salt": "LcnXkFBq",
                "md5": "0945ff84c37005726194b3f3c81bbb39",
                "sha1": "87945a6d1feae97e03cf92b166b0063b85328175",
                "sha256": "382f38e3f0105f0ddac0de9c10043f0928e471196d9e16204b4e2db0e00da62c"
            },
            "dob": {
                "date": "1958-06-04T08:53:39.167Z",
                "age": 63
            },
            "registered": {
                "date": "2008-04-08T08:12:25.490Z",
                "age": 13
            },
            "phone": "09-874-759",
            "cell": "041-737-00-52",
            "id": {
                "name": "HETU",
                "value": "NaNNA101undefined"
            },
            "picture": {
                "large": "https://randomuser.me/api/portraits/men/75.jpg",
                "medium": "https://randomuser.me/api/portraits/med/men/75.jpg",
                "thumbnail": "https://randomuser.me/api/portraits/thumb/men/75.jpg"
            },
            "nat": "FI"
        },
    ]
}

This is the approach I have taken but it doesn't seem to work:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:core';

class Profile {
  final String userName;
  final String name;
  final String emailId;
  final int timePeriod;
  final int age;
  final String nationality;
  final String number;
  final int streetNumber;
  final String streetName;
  final String city;
  final String country;
  final int postCode;
  final String picture;

  Profile({
    required this.userName,
    required this.name,
    required this.emailId,
    required this.timePeriod,
    required this.age,
    required this.nationality,
    required this.number,
    required this.streetNumber,
    required this.streetName,
    required this.city,
    required this.country,
    required this.postCode,
    required this.picture
  });
}

class ProfileProvider with ChangeNotifier {
  Map<String, Profile> _data = {};

  Map<String, Profile> get data {
    return {..._data};
  }

  Future<void> fetchData() async {
    final url = Uri.parse('https://randomuser.me/api/?results=50');
    final response = await http.get(url);
    final extractedData = json.decode(response.body);
    print(extractedData);
    Map<String, Profile> map = {};
    extractedData.forEach((key, value) =>           //51:19
        map.putIfAbsent(key, () =>                  //52:13
            Profile(
                userName: value['login']['username'],  //54:32
                name: value['name']['first'],
                emailId: value['email'],
                timePeriod: value['registered']['age'],
                age: value['dob']['age'],
                nationality: value['nat'],
                number: value['cell'],
                streetNumber: value['location']['street']['number'],
                streetName: value['location']['street']['name'],
                city: value['location']['city'],
                country: value['location']['country'],
                postCode: value['location']['postcode'],
                picture: value['picture']['large']
            )
        )
    );
    _data = map;
    notifyListeners();
  }
}

The way I see it, the problem lies from 54:32 onwards and I now have no idea how to get past it to get the code to work. I find this approach easy to understand so ideally would prefer the answers to be in the same but other approaches are welcome.

This is the error I get. The line numbers with the errors are marked in the code:

E/flutter (20478): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
E/flutter (20478): #0      ProfileProvider.fetchData.<anonymous closure>.<anonymous closure> (package:profile_app/provider/data.dart:54:32)
E/flutter (20478): #1      _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:311:23)
E/flutter (20478): #2      ProfileProvider.fetchData.<anonymous closure> (package:profile_app/provider/data.dart:52:13)
E/flutter (20478): #3      _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:397:8)
E/flutter (20478): #4      ProfileProvider.fetchData (package:profile_app/provider/data.dart:51:19)
E/flutter (20478): <asynchronous suspension>
E/flutter (20478): 

CodePudding user response:

the data type of "number" is int but you've added String. I'd recommend to manage Models in a separately. also for the beginning use json to dart and then use that class name to decode or encode the json response.

Profile profile = Profile.Fromjson(json.decode('String'));

CodePudding user response:

Try out below Model Class

class ProfileModel {
  ProfileModel({
    required this.results,
    required this.info,
  });
  late final List<Results> results;
  late final Info info;
  
  ProfileModel.fromJson(Map<String, dynamic> json){
    results = List.from(json['results']).map((e)=>Results.fromJson(e)).toList();
    info = Info.fromJson(json['info']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['results'] = results.map((e)=>e.toJson()).toList();
    _data['info'] = info.toJson();
    return _data;
  }
}

class Results {
  Results({
    required this.gender,
    required this.name,
    required this.location,
    required this.email,
    required this.login,
    required this.dob,
    required this.registered,
    required this.phone,
    required this.cell,
    required this.id,
    required this.picture,
    required this.nat,
  });
  late final String gender;
  late final Name name;
  late final Location location;
  late final String email;
  late final Login login;
  late final Dob dob;
  late final Registered registered;
  late final String phone;
  late final String cell;
  late final Id id;
  late final Picture picture;
  late final String nat;
  
  Results.fromJson(Map<String, dynamic> json){
    gender = json['gender'];
    name = Name.fromJson(json['name']);
    location = Location.fromJson(json['location']);
    email = json['email'];
    login = Login.fromJson(json['login']);
    dob = Dob.fromJson(json['dob']);
    registered = Registered.fromJson(json['registered']);
    phone = json['phone'];
    cell = json['cell'];
    id = Id.fromJson(json['id']);
    picture = Picture.fromJson(json['picture']);
    nat = json['nat'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['gender'] = gender;
    _data['name'] = name.toJson();
    _data['location'] = location.toJson();
    _data['email'] = email;
    _data['login'] = login.toJson();
    _data['dob'] = dob.toJson();
    _data['registered'] = registered.toJson();
    _data['phone'] = phone;
    _data['cell'] = cell;
    _data['id'] = id.toJson();
    _data['picture'] = picture.toJson();
    _data['nat'] = nat;
    return _data;
  }
}

class Name {
  Name({
    required this.title,
    required this.first,
    required this.last,
  });
  late final String title;
  late final String first;
  late final String last;
  
  Name.fromJson(Map<String, dynamic> json){
    title = json['title'];
    first = json['first'];
    last = json['last'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['title'] = title;
    _data['first'] = first;
    _data['last'] = last;
    return _data;
  }
}

class Location {
  Location({
    required this.street,
    required this.city,
    required this.state,
    required this.country,
    required this.postcode,
    required this.coordinates,
    required this.timezone,
  });
  late final Street street;
  late final String city;
  late final String state;
  late final String country;
  late final int? postcode;
  late final Coordinates coordinates;
  late final Timezone timezone;
  
  Location.fromJson(Map<String, dynamic> json){
    street = Street.fromJson(json['street']);
    city = json['city'];
    state = json['state'];
    country = json['country'];
    postcode = json['postcode'];
    coordinates = Coordinates.fromJson(json['coordinates']);
    timezone = Timezone.fromJson(json['timezone']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['street'] = street.toJson();
    _data['city'] = city;
    _data['state'] = state;
    _data['country'] = country;
    _data['postcode'] = postcode;
    _data['coordinates'] = coordinates.toJson();
    _data['timezone'] = timezone.toJson();
    return _data;
  }
}

class Street {
  Street({
    required this.number,
    required this.name,
  });
  late final int number;
  late final String name;
  
  Street.fromJson(Map<String, dynamic> json){
    number = json['number'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['number'] = number;
    _data['name'] = name;
    return _data;
  }
}

class Coordinates {
  Coordinates({
    required this.latitude,
    required this.longitude,
  });
  late final String latitude;
  late final String longitude;
  
  Coordinates.fromJson(Map<String, dynamic> json){
    latitude = json['latitude'];
    longitude = json['longitude'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['latitude'] = latitude;
    _data['longitude'] = longitude;
    return _data;
  }
}

class Timezone {
  Timezone({
    required this.offset,
    required this.description,
  });
  late final String offset;
  late final String description;
  
  Timezone.fromJson(Map<String, dynamic> json){
    offset = json['offset'];
    description = json['description'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['offset'] = offset;
    _data['description'] = description;
    return _data;
  }
}

class Login {
  Login({
    required this.uuid,
    required this.username,
    required this.password,
    required this.salt,
    required this.md5,
    required this.sha1,
    required this.sha256,
  });
  late final String uuid;
  late final String username;
  late final String password;
  late final String salt;
  late final String md5;
  late final String sha1;
  late final String sha256;
  
  Login.fromJson(Map<String, dynamic> json){
    uuid = json['uuid'];
    username = json['username'];
    password = json['password'];
    salt = json['salt'];
    md5 = json['md5'];
    sha1 = json['sha1'];
    sha256 = json['sha256'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['uuid'] = uuid;
    _data['username'] = username;
    _data['password'] = password;
    _data['salt'] = salt;
    _data['md5'] = md5;
    _data['sha1'] = sha1;
    _data['sha256'] = sha256;
    return _data;
  }
}

class Dob {
  Dob({
    required this.date,
    required this.age,
  });
  late final String date;
  late final int age;
  
  Dob.fromJson(Map<String, dynamic> json){
    date = json['date'];
    age = json['age'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['date'] = date;
    _data['age'] = age;
    return _data;
  }
}

class Registered {
  Registered({
    required this.date,
    required this.age,
  });
  late final String date;
  late final int age;
  
  Registered.fromJson(Map<String, dynamic> json){
    date = json['date'];
    age = json['age'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['date'] = date;
    _data['age'] = age;
    return _data;
  }
}

class Id {
  Id({
    required this.name,
     this.value,
  });
  late final String name;
  late final String? value;
  
  Id.fromJson(Map<String, dynamic> json){
    name = json['name'];
    value = json['value'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['name'] = name;
    _data['value'] = value;
    return _data;
  }
}

class Picture {
  Picture({
    required this.large,
    required this.medium,
    required this.thumbnail,
  });
  late final String large;
  late final String medium;
  late final String thumbnail;
  
  Picture.fromJson(Map<String, dynamic> json){
    large = json['large'];
    medium = json['medium'];
    thumbnail = json['thumbnail'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['large'] = large;
    _data['medium'] = medium;
    _data['thumbnail'] = thumbnail;
    return _data;
  }
}

class Info {
  Info({
    required this.seed,
    required this.results,
    required this.page,
    required this.version,
  });
  late final String seed;
  late final int results;
  late final int page;
  late final String version;
  
  Info.fromJson(Map<String, dynamic> json){
    seed = json['seed'];
    results = json['results'];
    page = json['page'];
    version = json['version'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['seed'] = seed;
    _data['results'] = results;
    _data['page'] = page;
    _data['version'] = version;
    return _data;
  }
}
  • Related