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": "claudine.damota#example.com",
"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": "lauri.autio#example.com",
"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):
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'));
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
I'm trying to return the items from this api https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812
but always the error:
Unhandled Exception: type 'List' is not a subtype of type 'Map<String, dynamic>'
this my object and model:
Future<ProdutoModel> getProduto() async {
try {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
_accountListModel = ProdutoModel.fromJson(res);
var data = res['filhos'] as List;
setState(() {
_list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
});
return _accountListModel;
} catch (e) {
rethrow;
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
return this api
The returned is at List, so you have to do something like:
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> main() async {
final response = await http.get(Uri.parse(
"https://api.maisdecristo.com/api/parents/mdcget00_parentkids/48984974812"));
var res = jsonDecode(response.body);
print(res);
var list = res as List;
for (var item in list) {
var _accountListModel = ProdutoModel.fromJson(item); // model per item
print(_accountListModel.phone);
var data = item['filhos'] as List;
var _list =
data.map<FilhoModel>((json) => FilhoModel.fromJson(json)).toList();
print(_list);
}
}
class ProdutoModel {
ProdutoModel({
required this.phone,
required this.desperson,
required this.desemail,
required this.filhos,
});
final String phone;
final String desperson;
final String desemail;
final List<FilhoModel> filhos;
factory ProdutoModel.fromJson(Map<String, dynamic> json) => ProdutoModel(
phone: json["phone"],
desperson: json["desperson"],
desemail: json["desemail"],
filhos: List<FilhoModel>.from(
json["filhos"].map((x) => FilhoModel.fromJson(x))),
);
}
class FilhoModel {
FilhoModel({
required this.age,
required this.firstname,
required this.lastname,
});
final int age;
final String firstname;
final String lastname;
factory FilhoModel.fromJson(Map<String, dynamic> json) => FilhoModel(
age: json["age"],
firstname: json["firstname"],
lastname: json["lastname"],
);
}
[
{
"phone": "48984974812",
"desperson": "Usuario admin",
"desemail": "admin#hcode.com.br",
"filhos": [
{
"age": 7,
"firstname": "Lorenzo",
"lastname": "Chaves"
},
{
"age": 14,
"firstname": "teste",
"lastname": "acompanhante"
},
{
"age": 14,
"firstname": "meu",
"lastname": "filho"
},
{
"age": 21,
"firstname": "teste",
"lastname": "teste"
}
]
}
]
You have type conversion issue make sure the types from the api is the same as the model
you can use this website : https://app.quicktype.io
to generate model to any json file without get any erorr and it gets you functions from json and to json
I am trying to handle a model which has a list but I stucking in between I am not getting any idea how to handle list which is in my model first of all I am getting data from api and I am storing Jason object in my model which is working perfect following is my json model
{
"statusCode": 200,
"success": true,
"messages": [],
"data": [
{
"id": 35,
"title": "Astrology",
"filename": "Astrology.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": []
},
{
"id": 36,
"title": "Muhurtam",
"filename": "Muhurtam.jpg",
"mimetype": "image/jpeg",
"directcalling": 1,
"parentid": null,
"subcat": [
{
"id": 50,
"title": "abc",
"filename": "abc.png",
"mimetype": "image/png",
"directcalling": 0,
"parentid": 36,
"subcat": []
}
now I am Saving above json object in below model following is my model class
class Data {
Data({
this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final Null parentid;
late final List<Subcat>? subcat;
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = null;
subcat = List.from(json['subcat']).map((e) => Subcat.fromJson(e)).toList();
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
// _data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
// _data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
// _data['parentid'] = parentid;
// _data['subcat'] = subcat.map((e) => e.toJson()).toList();
return _data;
}
}
class Subcat {
Subcat({
this.id,
required this.title,
required this.filename,
required this.mimetype,
required this.directcalling,
this.parentid,
this.subcat,
});
late final int? id;
late final String title;
late final String filename;
late final String mimetype;
late final int directcalling;
late final int? parentid;
late final List<dynamic>? subcat;
Subcat.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
filename = json['filename'];
mimetype = json['mimetype'];
directcalling = json['directcalling'];
parentid = json['parentid'];
subcat = List.castFrom<dynamic, dynamic>(json['subcat']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
//_data['id'] = id;
_data['title'] = title;
_data['filename'] = filename;
//_data['mimetype'] = mimetype;
_data['directcalling'] = directcalling;
//_data['parentid'] = parentid;
//_data['subcat'] = subcat;
return _data;
}
}
I am updating particular id in list:subcat which is in my Data class now I want to show changes to user after updating following is my update function
Data findById(int id) {
return categories!.data.firstWhere((cat) => cat.id == id);
}
Future<void> updateCatAtributes(
int id, BuildContext context, Subcat newCat, Data subid) async {
print('updating....${newCat.toJson()}');
final catIndex = subid.subcat!.indexWhere((prod) => prod.id == id);
if (catIndex >= 0) {
subid.subcat![catIndex] = newCat;
notifyListeners();
} else {
print('...');
}
following is my dropdown widget where I want to display changed title in my menu item
final loadedProduct = Provider.of<Category>(
context,
listen: false,
).findById(catId);
Consumer<Category>(
builder: (context, value, child) {
return Column(
children: [
DropdownButton<String>(
elevation: 16,
isExpanded: true,
hint: Text('please select sub category'),
items: loadedProduct.subcat!.map((v) {
return DropdownMenuItem<String>(
onTap: () {
subcat = v.id;
_initValues = {
'title': v.title,
};
},
value: v.title,
child: Text(v.title));
}).toList(),
onChanged: (val) {
value.updatesubcat(val!);
print(val);
},
value: value.sub,
),
],
In my flutter code I need to send array of objects on a http post request, but it can not be encoded as json object.
here is my flutter class to send data to the service
class JobCreateRequestModel {
String? category;
String? title;
String? description;
String? latitude;
String? longitude;
List<Job.Images>? images;
JobCreateRequestModel(
{this.category,
this.title,
this.description,
this.latitude,
this.longitude,
this.images});
Map<String?, dynamic> toJson() {
Map<String?, dynamic> map = {
category: category,
title: title,
description: description,
latitude: latitude,
longitude: longitude,
images: images
};
return map;
}
}
class Images {
String? id;
String? name;
String? type;
String? url;
double? size;
String? uploadedAt;
Images(Images item,
{this.id, this.name, this.type, this.url, this.size, this.uploadedAt});
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['name'] = this.name;
data['type'] = this.type;
data['url'] = this.url;
data['size'] = this.size;
data['uploadedAt'] = this.uploadedAt;
return data;
}
}
This class should be created this kind of object
{
"category": "1604173705548",
"title": "title",
"description": "For See More, We need to calculate how much text can be inserted in a given number of lines or Space.",
"latitude": "23.00343",
"longitude": "23.00343",
"images": [
{
"id": "16114286013370",
"name": "200820_4.jpeg",
"type": ".jpeg",
"url": "https://sample.com/job_images/16114286013370.jpeg",
"size": "72.369",
"uploadedAt": "1611428601337"
}
]
}
I have used form to get the required data to the model and need to convert it in to json encodable object. Any suggestion would be highly appreciated.
I used your JSON format to generate the model class :
import 'dart:convert';
JobCreateRequestModel jobCreateRequestModelFromJson(String str) => JobCreateRequestModel.fromJson(json.decode(str));
String jobCreateRequestModelToJson(JobCreateRequestModel data) => json.encode(data.toJson());
class JobCreateRequestModel {
JobCreateRequestModel({
this.category,
this.title,
this.description,
this.latitude,
this.longitude,
this.images,
});
String category;
String title;
String description;
String latitude;
String longitude;
List<Image> images;
factory JobCreateRequestModel.fromJson(Map<String, dynamic> json) => JobCreateRequestModel(
category: json["category"],
title: json["title"],
description: json["description"],
latitude: json["latitude"],
longitude: json["longitude"],
images: List<Image>.from(json["images"].map((x) => Image.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"category": category,
"title": title,
"description": description,
"latitude": latitude,
"longitude": longitude,
"images": List<dynamic>.from(images.map((x) => x.toJson())),
};
}
class Image {
Image({
this.id,
this.name,
this.type,
this.url,
this.size,
this.uploadedAt,
});
String id;
String name;
String type;
String url;
String size;
String uploadedAt;
factory Image.fromJson(Map<String, dynamic> json) => Image(
id: json["id"],
name: json["name"],
type: json["type"],
url: json["url"],
size: json["size"],
uploadedAt: json["uploadedAt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"type": type,
"url": url,
"size": size,
"uploadedAt": uploadedAt,
};
}
What you can do is simply while posting data to server use :
jobCreateRequestModelToJson(yourClassObject)
This should work! Hope this is what you wanted
in my application i get this result from server which into categories, that have an array which named products :
{
"categories": [
{
"id": 1,
"store_id": 1,
"category_id": null,
"page_id": null,
"title": "cat_name",
"image_uri": "/uploads/store/category_images/2020/1600839088.jpg",
"created_at": "2020-09-23T02:01:28.000000Z",
"updated_at": "2020-09-23T02:01:57.000000Z",
"products": [
{
"id": 1,
"store_categories_id": 1,
"store_id": 1,
"title": "title",
"description": "111111",
//...
}
]
}
],
"slides": {
"id": 1,
"slide_1": "/uploads/store/store_sliders/2020/16025126045410.jpg",
//...
}
}
i created this class with above structure:
StoreCategories class:
#JsonSerializable()
class StoreCategories {
final List<StoreCategoriesList> categories;
#JsonKey(nullable: true)
final Slides slides;
StoreCategories(this.categories,this.slides);
factory StoreCategories.fromJson(Map<String, dynamic> json) => _$StoreCategoriesFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesToJson(this);
}
StoreCategoriesList class:
#JsonSerializable()
class StoreCategoriesList{
final int id;
#JsonKey(name: 'store_id')
final int storeId;
final String title;
#JsonKey(name: 'image_uri')
final String imageUri;
#JsonKey(nullable: true)
final List<ProductsList> products;
StoreCategoriesList(this.id, this.storeId, this.title, this.imageUri, this.products);
factory StoreCategoriesList.fromJson(Map<String, dynamic> json) => _$StoreCategoriesListFromJson(json);
Map<String, dynamic> toJson() => _$StoreCategoriesListToJson(this);
}
ProductsList class:
#JsonSerializable()
class ProductsList {
final int id;
#JsonKey(name: 'store_categories_id')
final int storeCategoriesId;
#JsonKey(name: 'store_id')
final int storeId;
final String title;
final String description;
final String image;
final int cost;
ProductsList(this.id, this.storeCategoriesId, this.storeId, this.title, this.description, this.image, this.cost);
factory ProductsList.fromJson(Map<String, dynamic> json) => _$ProductsListFromJson(json);
Map<String, dynamic> toJson() => _$ProductsListToJson(this);
}
now! how can i convert my json structure to class map?
this code is not correct:
StoreCategories.fromJson(_res.response.data.map((data) => StoreCategories.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.fromJson(data)));
//StoreCategories.fromJson(_res.response.data.map((data) => List<StoreCategories>.from(data)));
Sounds like your _res.response.data is already a Map or List right?
So just simply StoreCategories.fromJson(_res.response.data). Done!
Flutter json_serializable is smart enough to decode nested classes! :)
P.S. If you have a JSON String, do jsonDecode(your_json_string) to get a Map or List.
I am having this type of response from API
{
"success": 1,
"data": [
{
"id": 539,
"user_id": 3115,
"amount": 5788,
"payment_gateway": "bank",
"message": "chchhb",
"status": "waiting",
"source": "everyone",
"created_ts": "2019-12-19 13:41:17",
"processed_ts": null
},
]
}
this is my model.dart
class Model {
final String status;
final List<String> data;
Model({
this.status,
this.data
});
factory Model.fromJson(Map<String, dynamic> parsedJson) {
var data = parsedJson['data'];
List<String> dataList = data.cast<String>();
return Model(
status: parsedJson['status'],
data: dataList
);
}
}
This is how I am fetching data from the model
Future<List<String>> getWithdrawals() async {
final userModel = Provider.of<UserModel>(context);
var userId = userModel.user.id;
Map<String, String> requestHeaders = {'Content-type': 'application/json'};
var body = {
'id': userId,
};
final response = await http.post(url);
if (response.statusCode == 200){
var jsonresponse = json.decode(response.body);
var withdrawals = WithdrawalModel.fromJson(jsonresponse);
return withdrawals.data;
} else {
print("Error" + response.body);
return null;
}
}
I am not able to display the data on the screen It is giving me an error like
type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String' in typecast
In FutureBuilder<List> I am not able to get data
I don't know where I am doing a mistake Please help...
I think your response type is not correct currently it's List<String> but it should be like List<Details> and you need to create another model class named Details (Or you can change the name).
You just put your response here. It will generate dart class models for you.
NOTE: you have to remove extra comma from your response to use model generator then your response will be like.
{
"success": 1,
"data": [
{
"id": 539,
"user_id": 3115,
"amount": 5788,
"payment_gateway": "bank",
"message": "chchhb",
"status": "waiting",
"source": "everyone",
"created_ts": "2019-12-19 13:41:17",
"processed_ts": null
}
]
}
Edit:
For example in your above model just change List type string to Details(Model) and vise-versa :
class Model {
final String status;
final List<Details> data; // Update string with model
}
Try this method
Future <PaymentReply> getPayment() async {
final userModel = Provider.of<UserModel>(context);
var userId = userModel.user.id;
try {
final response = await http.post(url,
headers: {
HttpHeaders.contentTypeHeader: "application/json"
},
body: '{\'id\':\''+ userId+'\'}', // You are not sending body in your code so check if it needs to be sent.
);
print(response.body); //CHECK IF THIS IS CORRECT RESPONSE AS EXPECTED
PaymentReply reply = paymentReplyFromJson(response.body);
return reply;
}on Exception catch (e){
print(e);
return PaymentReply();
}
}
with my modal
// To parse this JSON data, do
//
// final paymentReply = paymentReplyFromJson(jsonString);
import 'dart:convert';
PaymentReply paymentReplyFromJson(String str) => PaymentReply.fromJson(json.decode(str));
String paymentReplyToJson(PaymentReply data) => json.encode(data.toJson());
class PaymentReply {
int success;
List<Datum> data;
PaymentReply({
this.success,
this.data,
});
factory PaymentReply.fromJson(Map<String, dynamic> json) => PaymentReply(
success: json["success"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"success": success,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
int userId;
int amount;
String paymentGateway;
String message;
String status;
String source;
String createdTs;
String processedTs;
Datum({
this.id,
this.userId,
this.amount,
this.paymentGateway,
this.message,
this.status,
this.source,
this.createdTs,
this.processedTs,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
userId: json["user_id"],
amount: json["amount"],
paymentGateway: json["payment_gateway"],
message: json["message"],
status: json["status"],
source: json["source"],
createdTs: json["created_ts"],
processedTs: json["processed_ts"],
);
Map<String, dynamic> toJson() => {
"id": id,
"user_id": userId,
"amount": amount,
"payment_gateway": paymentGateway,
"message": message,
"status": status,
"source": source,
"created_ts": createdTs,
"processed_ts": processedTs,
};
}
My model was incorrect.
Solved by this model...
class WithdrawalModel {
final String status;
final String amount;
final List<Data> data;
WithdrawalModel({
this.status,
this.amount,
this.data
});
factory WithdrawalModel.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['data'] as List;
List<Data> dataList = list.map((i) => Data.fromJson(i)).toList();
return WithdrawalModel(
status: parsedJson['status'],
amount: parsedJson['amount'],
data: dataList
);
}
}
class Data {
int id;
int amount;
String message;
String status;
String source;
String createdTs;
Data({
this.id,
this.amount,
this.message,
this.status,
this.source,
this.createdTs
});
Data.fromJson(Map<String, dynamic> json) {
id = json['id'];
amount = json['amount'];
message = json['message'];
status = json['status'];
source = json['source'];
createdTs = json['created_ts'];
}
}