Flutter : JSON.parse fail on empty string - json

I am trying to parse JSON data in Flutter and it is working fine.
But when some data is empty or null then it is not working and giving error.
import 'dart:convert';
GetFollowing getFollowingFromJson(String str) => GetFollowing.fromJson(json.decode(str));
class GetFollowing {
List<Content> content;
int count;
bool success;
String error;
GetFollowing({
this.error,
this.content,
this.count,
this.success,
});
factory GetFollowing.fromJson(Map<String, dynamic> json) => GetFollowing(
error: json["error"],
content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
count: json["count"],
success: json["success"],
);
}
class Content {
int uid;
int following;
String name;
String profilePhoto;
String baseLocation;
String registrationDate;
String country;
Content({
this.uid,
this.following,
this.name,
this.profilePhoto,
this.baseLocation,
this.registrationDate,
this.country,
});
factory Content.fromJson(Map<String, dynamic> json) => Content(
uid: json["uid"] ?? null,
following: json["following"] ?? null,
name: json["name"] ?? null,
profilePhoto: json["profile_photo"] ?? null,
baseLocation: json["base_location"] ?? null,
registrationDate: json["registration_date"] ?? null,
country: json["country"] ?? null,
);
}
Here is the sample data.
Scenario
{"error":"No record found.","success":false}
Scenario
{
"content": [{
"uid": 34,
"following": 35,
"name": "Sadi",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 37,
"name": "Sameer",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}, {
"uid": 34,
"following": 36,
"name": "Simran",
"profile_photo": "noimage.png",
"base_location": "New Delhi",
"registration_date": "03-05-2020",
"country": "India"
}],
"count": 3,
"success": true
}
I am getting error if content is null or empty then parse didn't complete and gives error.
Exception Caught: NoSuchMethodError: The method '[]' was called on null.

content: (json["content"] as List).map((x as Map<String, dynamic>) => Content.fromJson(x)).toList()
Consider json_annotation or built_value to handle all your boiler plate for you.

Related

i cant figure out why this error type 'Null' is not a subtype of type 'int' in type cast

Flutter 3.3.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision b8f7f1f986 (hace 2 semanas) • 2022-11-23 06:43:51 +0900
Engine • revision 8f2221fbef
Tools • Dart 2.18.5 • DevTools 2.15.0
hello, best regards and I hope you are well, I have spent the last few hours trying to solve the error in the title of the issue, and I have not been able to, could you explain to me a way to solve it, I have attached the model that I am using and the response of the request to an api, thank you very much in advance
base_response_model.dart
import 'package:json_annotation/json_annotation.dart';
part 'base_response_model.g.dart';
#JsonSerializable()
class BaseResponseModel {
final int page;
#JsonKey(name: 'page_size')
final int pageSize;
final int total;
final int pages;
#JsonKey(name: 'prev_page', defaultValue: 0)
final dynamic prevPage;
#JsonKey(name: 'next_page', defaultValue: 0)
final dynamic nextPage;
BaseResponseModel({
required this.page,
required this.pageSize,
required this.total,
required this.pages,
required this.prevPage,
required this.nextPage,
});
factory BaseResponseModel.fromJson(Map<String, dynamic> json) =>
_$BaseResponseModelFromJson(json);
Map<String, dynamic> toJson() => _$BaseResponseModelToJson(this);
}
get_municipalities_by_province_response_model.dart
import 'package:delivery/app/data/models/andariego/andariego_models/municipality_model.dart';
import 'package:delivery/app/data/models/andariego/andariego_response_models/base_response_model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'get_municipalities_by_province_response_model.g.dart';
#JsonSerializable()
class GetMunicipalitiesByProvinceResponseModel extends BaseResponseModel {
final List<MunicipalityModel> data;
GetMunicipalitiesByProvinceResponseModel({
required super.page,
required super.pageSize,
required super.total,
required super.pages,
required super.prevPage,
required super.nextPage,
required this.data,
});
factory GetMunicipalitiesByProvinceResponseModel.fromJson(
Map<String, dynamic> json) =>
_$GetMunicipalitiesByProvinceResponseModelFromJson(json);
#override
Map<String, dynamic> toJson() =>
_$GetMunicipalitiesByProvinceResponseModelToJson(this);
}
municipality_model.dart
import 'package:delivery/app/data/models/andariego/andariego_models/base_andariego_model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'municipality_model.g.dart';
#JsonSerializable()
class MunicipalityModel extends BaseAndariegoModel {
final int parent;
MunicipalityModel({
required super.id,
required super.name,
required this.parent,
});
factory MunicipalityModel.fromJson(Map<String, dynamic> json) =>
_$MunicipalityModelFromJson(json);
#override
Map<String, dynamic> toJson() => _$MunicipalityModelToJson(this);
}
api_response.json
{
"page": 1,
"page_size": 20,
"total": 11,
"pages": 1,
"prev_page": null,
"next_page": null,
"data": [
{
"id": 1188,
"name": "Consolación del Sur",
"parent": 58
},
{
"id": 1132,
"name": "Guane",
"parent": 58
},
{
"id": 1125,
"name": "La Palma",
"parent": 58
},
{
"id": 1124,
"name": "Los Palacios",
"parent": 58
},
{
"id": 1186,
"name": "Mantua",
"parent": 58
},
{
"id": 1182,
"name": "Minas de Matahambre",
"parent": 58
},
{
"id": 1189,
"name": "Pinar del Rio",
"parent": 58
},
{
"id": 1165,
"name": "Sandino",
"parent": 58
},
{
"id": 1133,
"name": "San Juan y Martínez",
"parent": 58
},
{
"id": 1187,
"name": "San Luis",
"parent": 58
},
{
"id": 1169,
"name": "Viñales",
"parent": 58
}
]
}
Generated code
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'base_response_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BaseResponseModel _$BaseResponseModelFromJson(Map<String, dynamic> json) =>
BaseResponseModel(
page: json['page'] as int,
pageSize: json['page_size'] as int,
total: json['total'] as int,
pages: json['pages'] as int,
prevPage: json['prev_page'] ?? 0,
nextPage: json['next_page'] ?? 0,
);
Map<String, dynamic> _$BaseResponseModelToJson(BaseResponseModel instance) =>
<String, dynamic>{
'page': instance.page,
'page_size': instance.pageSize,
'total': instance.total,
'pages': instance.pages,
'prev_page': instance.prevPage,
'next_page': instance.nextPage,
};
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'get_municipalities_by_province_response_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
GetMunicipalitiesByProvinceResponseModel
_$GetMunicipalitiesByProvinceResponseModelFromJson(
Map<String, dynamic> json) =>
GetMunicipalitiesByProvinceResponseModel(
page: json['page'] as int,
pageSize: json['page_size'] as int,
total: json['total'] as int,
pages: json['pages'] as int,
prevPage: json['prev_page'] ?? 0,
nextPage: json['next_page'] ?? 0,
data: (json['data'] as List<dynamic>)
.map((e) => MunicipalityModel.fromJson(e as Map<String, dynamic>))
.toList(),
);
Map<String, dynamic> _$GetMunicipalitiesByProvinceResponseModelToJson(
GetMunicipalitiesByProvinceResponseModel instance) =>
<String, dynamic>{
'page': instance.page,
'page_size': instance.pageSize,
'total': instance.total,
'pages': instance.pages,
'prev_page': instance.prevPage,
'next_page': instance.nextPage,
'data': instance.data,
};
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'municipality_model.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
MunicipalityModel _$MunicipalityModelFromJson(Map<String, dynamic> json) =>
MunicipalityModel(
id: json['id'] as int,
name: json['name'] as String,
parent: json['parent'] as int,
);
Map<String, dynamic> _$MunicipalityModelToJson(MunicipalityModel instance) =>
<String, dynamic>{
'id': instance.id,
'name': instance.name,
'parent': instance.parent,
};
I am using flutter, null safety
It looks like a field is missing (or null) in the JSON causing that problem. The line number should point you to the right spot!

Flutter jsonDecode returns String instead of List

I want to decode my json to a List but jsonDecode returns String instead of List.
My JSON:
[{
"TicketID": 31,
"EmpID": "11553",
"Name": "Test",
"Location": null,
"PhoneExt": 345345,
"Code": null,
"Reason": null,
"Category": null,
"Created": null,
"Username": "abc",
"OtherLocation": null,
"Room": null,
"Floor": null,
"CodeBlueDone": null,
"CodeBlueDoneDate": null,
"LocationCode": null,
"PatientType": null,
"EmergencyType": "Emergency",
"FilledDateTime": null,
"SubmitDateTime": null,
"Type": null,
"CallTime": "2022-08-26T13:43:25.003",
"Status": "New"
}, {
"TicketID": 30,
"EmpID": "12",
"Name": "dbdb",
"Location": null,
"PhoneExt": 123,
"Code": null,
"Reason": null,
"Category": null,
"Created": null,
"Username": "abc",
"OtherLocation": null,
"Room": null,
"Floor": null,
"CodeBlueDone": null,
"CodeBlueDoneDate": null,
"LocationCode": null,
"PatientType": null,
"EmergencyType": "Emergency",
"FilledDateTime": null,
"SubmitDateTime": null,
"Type": null,
"CallTime": "2022-08-25T21:14:39.807",
"Status": "New"
}]
if (response.statusCode == 200) {
jsonDecode(response.body);
print(jsonDecode(response.body).runtimeType);
}
Future<List> _getDataFromWeb() async {
try {
await http.post(
Uri.parse(apiURL),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
).then((response) {
if (response.statusCode == 200) {
try {
final resp = jsonDecode(response.body) as List?;
print(resp.runtimeType);
} catch (ex) {
print("_getDataFromWeb() error: ${ex}");
}
} else if (response.statusCode == 404) {
print("Error 404: ${response.statusCode}");
} else {
print("Error: ${response.statusCode}");
}
}).catchError((error) {
print("Error: " + error);
});
} catch (ex) {
print("API-ERR: $ex");
}
}
Full code to decode is given above
Why the flutter jsonDecode or json.Decode doesn't return a List from above JSON?
EDIT
Calling jsonDecode two times works and returns List
final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);
I wonder why calling jsonDecode() two times is needed?
Calling jsonDecode two times works and returns List
final resp = jsonDecode(jsonDecode(response.body));
print(resp.runtimeType);
Finally found the answer after investing hours into it.
Try like this
final response = jsonDecode(response.body) as List?;
print(response.runtimeType);
Try this code via QuickType
// To parse this JSON data, do
//
// final model = modelFromJson(jsonString);
import 'dart:convert';
List<Model> modelFromJson(String str) => List<Model>.from(json.decode(str).map((x) => Model.fromJson(x)));
String modelToJson(List<Model> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Model {
Model({
this.ticketId,
this.empId,
this.name,
this.location,
this.phoneExt,
this.code,
this.reason,
this.category,
this.created,
this.username,
this.otherLocation,
this.room,
this.floor,
this.codeBlueDone,
this.codeBlueDoneDate,
this.locationCode,
this.patientType,
this.emergencyType,
this.filledDateTime,
this.submitDateTime,
this.type,
this.callTime,
this.status,
});
int ticketId;
String empId;
String name;
dynamic location;
int phoneExt;
dynamic code;
dynamic reason;
dynamic category;
dynamic created;
String username;
dynamic otherLocation;
dynamic room;
dynamic floor;
dynamic codeBlueDone;
dynamic codeBlueDoneDate;
dynamic locationCode;
dynamic patientType;
String emergencyType;
dynamic filledDateTime;
dynamic submitDateTime;
dynamic type;
DateTime callTime;
String status;
factory Model.fromJson(Map<String, dynamic> json) => Model(
ticketId: json["TicketID"],
empId: json["EmpID"],
name: json["Name"],
location: json["Location"],
phoneExt: json["PhoneExt"],
code: json["Code"],
reason: json["Reason"],
category: json["Category"],
created: json["Created"],
username: json["Username"],
otherLocation: json["OtherLocation"],
room: json["Room"],
floor: json["Floor"],
codeBlueDone: json["CodeBlueDone"],
codeBlueDoneDate: json["CodeBlueDoneDate"],
locationCode: json["LocationCode"],
patientType: json["PatientType"],
emergencyType: json["EmergencyType"],
filledDateTime: json["FilledDateTime"],
submitDateTime: json["SubmitDateTime"],
type: json["Type"],
callTime: DateTime.parse(json["CallTime"]),
status: json["Status"],
);
Map<String, dynamic> toJson() => {
"TicketID": ticketId,
"EmpID": empId,
"Name": name,
"Location": location,
"PhoneExt": phoneExt,
"Code": code,
"Reason": reason,
"Category": category,
"Created": created,
"Username": username,
"OtherLocation": otherLocation,
"Room": room,
"Floor": floor,
"CodeBlueDone": codeBlueDone,
"CodeBlueDoneDate": codeBlueDoneDate,
"LocationCode": locationCode,
"PatientType": patientType,
"EmergencyType": emergencyType,
"FilledDateTime": filledDateTime,
"SubmitDateTime": submitDateTime,
"Type": type,
"CallTime": callTime.toIso8601String(),
"Status": status,
};
}
Make sure response.body is in correct type and format. And try decoding via this code:
final List<dynamic> decodedResponseBody = jsonDecode(response.body);
resource: https://api.flutter.dev/flutter/dart-convert/jsonDecode.html
Try
json.decode(response.body) as List;
EDIT
Try this format
Future<List> _getDataFromWeb() async {
try {
var response = await http.post(
Uri.parse(apiURL),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
);
if (response.statusCode == 200) {
try {
final resp = json.decode(response.body.toString()) as List?;
print(resp.runtimeType);
} catch (ex) {
print("_getDataFromWeb() error: ${ex}");
}
} else if (response.statusCode == 404) {
print("Error 404: ${response.statusCode}");
} else {
print("Error: ${response.statusCode}");
}
}
} catch (ex) {
print("API-ERR: $ex");
}
}

Parsing JSON in flutter cast<RK, RV>() => Map<RK, RV>, No such method error

Future<List<CurrentUser>> getCurrUserSettings() async {
int id = await getCurrentUser();
print(id);
final _storage = FlutterSecureStorage();
_token = await _storage.read(key: "token");
var api = API();
// TODO resolve id so that we have it on the start and not called everytime
String newUrl = "${api.baseUrl}${api.cuUser}$id";
var url = Uri.parse(newUrl);
var response = await http.get(
url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': "Bearer $_token",
},
);
if (response.statusCode == 200) {
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
return parsed
.map<CurrentUser>((json) => CurrentUser.fromJson(json))
.toList();
} else {
print(response.statusCode);
}
return null; }
This is the code I am using to call current user data. This function returns a list. I have made many other API calls with the same technique and all of them are working perfectly fine but only in this method I am getting the following error.
E/flutter (14954): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
E/flutter (14954): Receiver: _LinkedHashMap len:16
E/flutter (14954): Tried calling: cast<Map<String, dynamic>>()
E/flutter (14954): Found: cast<RK, RV>() => Map<RK, RV>
E/flutter (14954): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
E/flutter (14954): #1 AuthService.getCurrUserSettings
package:App/…/Services/Auth.dart:73
E/flutter (14954): <asynchronous suspension>
E/flutter (14954): #2 DrawerUserInfo.getUserInfo
package:App/…/components/drawerProvider.dart:10
E/flutter (14954): <asynchronous suspension>
I am also sharing the model file too please take a look. I am stuck with this for a while I have used many different models and the error is same in every model.
Response Json
{
"id": 3,
"username": "PlayPizza",
"email": "play#pizza.com",
"provider": "local",
"confirmed": true,
"blocked": null,
"role": {
"id": 1,
"name": "Authenticated",
"description": "Default role given to authenticated user.",
"type": "authenticated"
},
"displayName": "PlayPizza",
"user_information": {
"id": 1,
"country": "India",
"state": "Delhi",
"address": "Some address",
"postalcode": "110092",
"users_permissions_user": 3,
"published_at": "2021-07-04T21:24:46.324Z",
"created_at": "2021-07-04T21:24:43.063Z",
"updated_at": "2021-07-04T21:24:46.409Z",
"certificate": {
"id": 1,
"name": "1_9cb3b3b033.jpg",
"alternativeText": "",
"caption": "",
"width": 300,
"height": 300,
"formats": {
"thumbnail": {
"ext": ".jpg",
"url": "/uploads/thumbnail_1_9cb3b3b033_7980eea4f5.jpg",
"hash": "thumbnail_1_9cb3b3b033_7980eea4f5",
"mime": "image/jpeg",
"name": "thumbnail_1_9cb3b3b033.jpg",
"path": null,
"size": 2.48,
"width": 156,
"height": 156
}
},
"hash": "1_9cb3b3b033_7980eea4f5",
"ext": ".jpg",
"mime": "image/jpeg",
"size": 5.28,
"url": "/uploads/1_9cb3b3b033_7980eea4f5.jpg",
"previewUrl": null,
"provider": "local",
"provider_metadata": null,
"created_at": "2021-07-04T15:03:55.744Z",
"updated_at": "2021-07-04T15:03:55.798Z"
}
},
"feedback": "hello",
"created_at": "2021-07-04T19:59:30.024Z",
"updated_at": "2021-07-04T21:26:41.314Z",
"avatar": {
"id": 10,
"name": "customer_3_008140d19d.png",
"alternativeText": "",
"caption": "",
"width": 180,
"height": 180,
"formats": {
"thumbnail": {
"ext": ".png",
"url": "/uploads/thumbnail_customer_3_008140d19d_a96cc0a5e3.png",
"hash": "thumbnail_customer_3_008140d19d_a96cc0a5e3",
"mime": "image/png",
"name": "thumbnail_customer_3_008140d19d.png",
"path": null,
"size": 62.71,
"width": 156,
"height": 156
}
},
"hash": "customer_3_008140d19d_a96cc0a5e3",
"ext": ".png",
"mime": "image/png",
"size": 65.81,
"url": "/uploads/customer_3_008140d19d_a96cc0a5e3.png",
"previewUrl": null,
"provider": "local",
"provider_metadata": null,
"created_at": "2021-07-04T17:59:44.000Z",
"updated_at": "2021-07-04T17:59:44.024Z"
},
"user_categories": [
{
"id": 1,
"categoryName": "GymGoer",
"users_permissions_user": 3,
"published_at": "2021-07-04T15:53:43.824Z",
"created_at": "2021-07-04T15:53:39.228Z",
"updated_at": "2021-07-04T21:26:41.307Z"
}
],
"workoutplaces": [
{
"id": 2,
"title": "Gym Nation",
"description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
"location": "145 Marlee Ave, York, ON M6B 3H3, Canada",
"price": 88.26,
"rating": 4.5,
"latitude": 43.80946617910369,
"longitude": -79.26975142707997,
"users_permissions_user": 3,
"published_at": "2021-07-04T17:09:53.162Z",
"created_at": "2021-07-04T17:09:50.238Z",
"updated_at": "2021-07-04T21:26:41.308Z",
"coverimg": {
"id": 8,
"name": "large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3.jpg",
"alternativeText": "",
"caption": "",
"width": 1000,
"height": 666,
"formats": {
"small": {
"ext": ".jpg",
"url": "/uploads/small_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916.jpg",
"hash": "small_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916",
"mime": "image/jpeg",
"name": "small_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3.jpg",
"path": null,
"size": 27.34,
"width": 500,
"height": 333
},
"medium": {
"ext": ".jpg",
"url": "/uploads/medium_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916.jpg",
"hash": "medium_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916",
"mime": "image/jpeg",
"name": "medium_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3.jpg",
"path": null,
"size": 48.79,
"width": 750,
"height": 500
},
"thumbnail": {
"ext": ".jpg",
"url": "/uploads/thumbnail_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916.jpg",
"hash": "thumbnail_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916",
"mime": "image/jpeg",
"name": "thumbnail_large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3.jpg",
"path": null,
"size": 9.3,
"width": 234,
"height": 156
}
},
"hash": "large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916",
"ext": ".jpg",
"mime": "image/jpeg",
"size": 74.23,
"url": "/uploads/large_sule_makaroglu_Y_Fmvj_O3_TP_s_unsplash_c546ce68c3_fe08736916.jpg",
"previewUrl": null,
"provider": "local",
"provider_metadata": null,
"created_at": "2021-07-04T17:05:47.094Z",
"updated_at": "2021-07-04T17:05:47.104Z"
}
}
],
"upcomming_classes": [
{
"id": 1,
"name": "Yoga house",
"description": "Some Description",
"date": "2021-07-13",
"time": "01:30:00",
"confirmed": true,
"paid": true,
"price": 59.33,
"workoutplace": 1,
"users_permissions_user": 3,
"month": "July",
"published_at": null,
"created_at": "2021-07-04T21:26:23.276Z",
"updated_at": "2021-07-04T21:26:41.309Z"
}
]}
Model File
import 'dart:convert';
CurrentUser currentUserFromJson(String str) =>
CurrentUser.fromJson(json.decode(str));
String currentUserToJson(CurrentUser data) => json.encode(data.toJson());
class CurrentUser {
CurrentUser({
this.id,
this.username,
this.email,
this.provider,
this.confirmed,
this.blocked,
this.role,
this.displayName,
this.userInformation,
this.feedback,
this.createdAt,
this.updatedAt,
this.avatar,
this.userCategories,
this.workoutplaces,
this.upcommingClasses,
});
int id;
String username;
String email;
String provider;
bool confirmed;
dynamic blocked;
Role role;
String displayName;
UserInformation userInformation;
String feedback;
DateTime createdAt;
DateTime updatedAt;
Avatar avatar;
List<UserCategory> userCategories;
List<Workoutplace> workoutplaces;
List<UpcommingClass> upcommingClasses;
factory CurrentUser.fromJson(Map<String, dynamic> json) => CurrentUser(
id: json["id"],
username: json["username"],
email: json["email"],
provider: json["provider"],
confirmed: json["confirmed"],
blocked: json["blocked"],
role: Role.fromJson(json["role"]),
displayName: json["displayName"],
userInformation: UserInformation.fromJson(json["user_information"]),
feedback: json["feedback"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
avatar: Avatar.fromJson(json["avatar"]),
userCategories: List<UserCategory>.from(
json["user_categories"].map((x) => UserCategory.fromJson(x))),
workoutplaces: List<Workoutplace>.from(
json["workoutplaces"].map((x) => Workoutplace.fromJson(x))),
upcommingClasses: List<UpcommingClass>.from(
json["upcomming_classes"].map((x) => UpcommingClass.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"username": username,
"email": email,
"provider": provider,
"confirmed": confirmed,
"blocked": blocked,
"role": role.toJson(),
"displayName": displayName,
"user_information": userInformation.toJson(),
"feedback": feedback,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"avatar": avatar.toJson(),
"user_categories":
List<dynamic>.from(userCategories.map((x) => x.toJson())),
"workoutplaces":
List<dynamic>.from(workoutplaces.map((x) => x.toJson())),
"upcomming_classes":
List<dynamic>.from(upcommingClasses.map((x) => x.toJson())),
};
}
class Avatar {
Avatar({
this.id,
this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt,
});
int id;
String name;
String alternativeText;
String caption;
int width;
int height;
AvatarFormats formats;
String hash;
String ext;
String mime;
double size;
String url;
dynamic previewUrl;
String provider;
dynamic providerMetadata;
DateTime createdAt;
DateTime updatedAt;
factory Avatar.fromJson(Map<String, dynamic> json) => Avatar(
id: json["id"],
name: json["name"],
alternativeText: json["alternativeText"],
caption: json["caption"],
width: json["width"],
height: json["height"],
formats: AvatarFormats.fromJson(json["formats"]),
hash: json["hash"],
ext: json["ext"],
mime: json["mime"],
size: json["size"].toDouble(),
url: json["url"],
previewUrl: json["previewUrl"],
provider: json["provider"],
providerMetadata: json["provider_metadata"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"alternativeText": alternativeText,
"caption": caption,
"width": width,
"height": height,
"formats": formats.toJson(),
"hash": hash,
"ext": ext,
"mime": mime,
"size": size,
"url": url,
"previewUrl": previewUrl,
"provider": provider,
"provider_metadata": providerMetadata,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class AvatarFormats {
AvatarFormats({
this.thumbnail,
});
Thumbnail thumbnail;
factory AvatarFormats.fromJson(Map<String, dynamic> json) => AvatarFormats(
thumbnail: Thumbnail.fromJson(json["thumbnail"]),
);
Map<String, dynamic> toJson() => {
"thumbnail": thumbnail.toJson(),
};
}
class Thumbnail {
Thumbnail({
this.ext,
this.url,
this.hash,
this.mime,
this.name,
this.path,
this.size,
this.width,
this.height,
});
String ext;
String url;
String hash;
String mime;
String name;
dynamic path;
double size;
int width;
int height;
factory Thumbnail.fromJson(Map<String, dynamic> json) => Thumbnail(
ext: json["ext"],
url: json["url"],
hash: json["hash"],
mime: json["mime"],
name: json["name"],
path: json["path"],
size: json["size"].toDouble(),
width: json["width"],
height: json["height"],
);
Map<String, dynamic> toJson() => {
"ext": ext,
"url": url,
"hash": hash,
"mime": mime,
"name": name,
"path": path,
"size": size,
"width": width,
"height": height,
};
}
class Role {
Role({
this.id,
this.name,
this.description,
this.type,
});
int id;
String name;
String description;
String type;
factory Role.fromJson(Map<String, dynamic> json) => Role(
id: json["id"],
name: json["name"],
description: json["description"],
type: json["type"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
"type": type,
};
}
class UpcommingClass {
UpcommingClass({
this.id,
this.name,
this.description,
this.date,
this.time,
this.confirmed,
this.paid,
this.price,
this.workoutplace,
this.usersPermissionsUser,
this.month,
this.publishedAt,
this.createdAt,
this.updatedAt,
});
int id;
String name;
String description;
DateTime date;
String time;
bool confirmed;
bool paid;
double price;
int workoutplace;
int usersPermissionsUser;
String month;
dynamic publishedAt;
DateTime createdAt;
DateTime updatedAt;
factory UpcommingClass.fromJson(Map<String, dynamic> json) => UpcommingClass(
id: json["id"],
name: json["name"],
description: json["description"],
date: DateTime.parse(json["date"]),
time: json["time"],
confirmed: json["confirmed"],
paid: json["paid"],
price: json["price"].toDouble(),
workoutplace: json["workoutplace"],
usersPermissionsUser: json["users_permissions_user"],
month: json["month"],
publishedAt: json["published_at"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"description": description,
"date":
"${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
"time": time,
"confirmed": confirmed,
"paid": paid,
"price": price,
"workoutplace": workoutplace,
"users_permissions_user": usersPermissionsUser,
"month": month,
"published_at": publishedAt,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class UserCategory {
UserCategory({
this.id,
this.categoryName,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt,
});
int id;
String categoryName;
int usersPermissionsUser;
DateTime publishedAt;
DateTime createdAt;
DateTime updatedAt;
factory UserCategory.fromJson(Map<String, dynamic> json) => UserCategory(
id: json["id"],
categoryName: json["categoryName"],
usersPermissionsUser: json["users_permissions_user"],
publishedAt: DateTime.parse(json["published_at"]),
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"categoryName": categoryName,
"users_permissions_user": usersPermissionsUser,
"published_at": publishedAt.toIso8601String(),
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class UserInformation {
UserInformation({
this.id,
this.country,
this.state,
this.address,
this.postalcode,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt,
this.certificate,
});
int id;
String country;
String state;
String address;
String postalcode;
int usersPermissionsUser;
DateTime publishedAt;
DateTime createdAt;
DateTime updatedAt;
Avatar certificate;
factory UserInformation.fromJson(Map<String, dynamic> json) =>
UserInformation(
id: json["id"],
country: json["country"],
state: json["state"],
address: json["address"],
postalcode: json["postalcode"],
usersPermissionsUser: json["users_permissions_user"],
publishedAt: DateTime.parse(json["published_at"]),
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
certificate: Avatar.fromJson(json["certificate"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"country": country,
"state": state,
"address": address,
"postalcode": postalcode,
"users_permissions_user": usersPermissionsUser,
"published_at": publishedAt.toIso8601String(),
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"certificate": certificate.toJson(),
};
}
class Workoutplace {
Workoutplace({
this.id,
this.title,
this.description,
this.location,
this.price,
this.rating,
this.latitude,
this.longitude,
this.usersPermissionsUser,
this.publishedAt,
this.createdAt,
this.updatedAt,
this.coverimg,
});
int id;
String title;
String description;
String location;
double price;
double rating;
double latitude;
double longitude;
int usersPermissionsUser;
DateTime publishedAt;
DateTime createdAt;
DateTime updatedAt;
Coverimg coverimg;
factory Workoutplace.fromJson(Map<String, dynamic> json) => Workoutplace(
id: json["id"],
title: json["title"],
description: json["description"],
location: json["location"],
price: json["price"].toDouble(),
rating: json["rating"].toDouble(),
latitude: json["latitude"].toDouble(),
longitude: json["longitude"].toDouble(),
usersPermissionsUser: json["users_permissions_user"],
publishedAt: DateTime.parse(json["published_at"]),
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
coverimg: Coverimg.fromJson(json["coverimg"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"description": description,
"location": location,
"price": price,
"rating": rating,
"latitude": latitude,
"longitude": longitude,
"users_permissions_user": usersPermissionsUser,
"published_at": publishedAt.toIso8601String(),
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
"coverimg": coverimg.toJson(),
};
}
class Coverimg {
Coverimg({
this.id,
this.name,
this.alternativeText,
this.caption,
this.width,
this.height,
this.formats,
this.hash,
this.ext,
this.mime,
this.size,
this.url,
this.previewUrl,
this.provider,
this.providerMetadata,
this.createdAt,
this.updatedAt,
});
int id;
String name;
String alternativeText;
String caption;
int width;
int height;
CoverimgFormats formats;
String hash;
String ext;
String mime;
double size;
String url;
dynamic previewUrl;
String provider;
dynamic providerMetadata;
DateTime createdAt;
DateTime updatedAt;
factory Coverimg.fromJson(Map<String, dynamic> json) => Coverimg(
id: json["id"],
name: json["name"],
alternativeText: json["alternativeText"],
caption: json["caption"],
width: json["width"],
height: json["height"],
formats: CoverimgFormats.fromJson(json["formats"]),
hash: json["hash"],
ext: json["ext"],
mime: json["mime"],
size: json["size"].toDouble(),
url: json["url"],
previewUrl: json["previewUrl"],
provider: json["provider"],
providerMetadata: json["provider_metadata"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"alternativeText": alternativeText,
"caption": caption,
"width": width,
"height": height,
"formats": formats.toJson(),
"hash": hash,
"ext": ext,
"mime": mime,
"size": size,
"url": url,
"previewUrl": previewUrl,
"provider": provider,
"provider_metadata": providerMetadata,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class CoverimgFormats {
CoverimgFormats({
this.small,
this.medium,
this.thumbnail,
});
Thumbnail small;
Thumbnail medium;
Thumbnail thumbnail;
factory CoverimgFormats.fromJson(Map<String, dynamic> json) =>
CoverimgFormats(
small: Thumbnail.fromJson(json["small"]),
medium: Thumbnail.fromJson(json["medium"]),
thumbnail: Thumbnail.fromJson(json["thumbnail"]),
);
Map<String, dynamic> toJson() => {
"small": small.toJson(),
"medium": medium.toJson(),
"thumbnail": thumbnail.toJson(),
};
}
the thing is that in your response you don't have a list of the users, you only have one user and you are trying to parse it to a list of the users. So, please replace
final parsed = jsonDecode(response.body).cast<Map<String, dynamic>>();
return parsed
.map<CurrentUser>((json) => CurrentUser.fromJson(json))
.toList();
With parsing to single user:
final parsed = json.decode(resource);
final user = CurrentUser.fromJson(parsed);

Not able to parse json data in flutter

I am not able to parse below mentioned json data in flutter.
[
{
"id": 96,
"name": "Entertainment",
"link": "https://thehappilyeverafter.in/listing-category/entertainment/",
"image": "https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg",
"children": [
{
"child_id": 114,
"child_name": "DJs",
"child_link": "https://thehappilyeverafter.in/listing-category/djs/"
},
{
"child_id": 117,
"child_name": "Live Music",
"child_link": "https://thehappilyeverafter.in/listing-category/live-music/"
},
{
"child_id": 115,
"child_name": "Wedding Choreographer",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-choreographer/"
},
{
"child_id": 116,
"child_name": "Wedding Entertainment",
"child_link": "https://thehappilyeverafter.in/listing-category/wedding-entertainment/"
}
]
}
]`
import 'dart:convert';
List<Root> rootFromJson(String str) => List<Root>.from(json.decode(str).map((x) => Root.fromJson(x)));
String rootToJson(List<Root> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Root {
Root({
this.id,
this.name,
this.link,
this.image,
this.children,
});
int id;
String name;
String link;
String image;
List<Children> children;
factory Root.fromJson(Map<String, dynamic> json) => Root(
id: json["id"],
name: json["name"],
link: json["link"],
image: json["image"] == null ? null : json["image"],
children: List<Children>.from(json["children"].map((x) => Children.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"link": link,
"image": image == null ? null : image,
"children": List<dynamic>.from(children.map((x) => x.toJson())),
};
}
class Children {
Children({
this.childId,
this.childName,
this.childLink,
});
int childId;
String childName;
String childLink;
factory Children.fromJson(Map<String, dynamic> json) => Children(
childId: json["child_id"],
childName: json["child_name"],
childLink: json["child_link"],
);
Map<String, dynamic> toJson() => {
"child_id": childId,
"child_name": childName,
"child_link": childLink,
};
}
[Getting this error][1]
`
type 'List' is not a subtype of type 'Children'
Since your json is a list, you should loop through it:
final List<Root> roots = yourJson.map((element) {
return Root.fromJson(element);
}).toList();
print(roots.first.image);
//https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg

How to get json array in Flutter/Dart

I would want to get the data for all "name" only from the array data.
I want to print(data['data']['name']);
But it returns this error:
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
But when I print(data['data']);, it will return all data from "data":
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
......
],
Call API Code
displayBanks(BuildContext context) async {
_callApi.refreshTokenApi(context);
var _addressUrl = '$_hostUrl/banks'; //API URL
final SharedPreferences prefs = await SharedPreferences.getInstance();
_accessToken = prefs.getString('access_token');
Response _response = await get(_addressUrl, headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $_accessToken'
});
var data;
data = jsonDecode(_response.body);
if (_response.statusCode == 200) {
print(data['data']['name']);
return data;
}
else {
print(_response.statusCode);
}
}
SAMPLE JSON DATA FROM API URL:
{
"data": [
{
"created_at": "2020-03-16 16:10:51",
"deleted_at": null,
"id": 2,
"is_active": 1,
"name": "Maybank",
"updated_at": "2020-03-16 16:18:06"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 3,
"is_active": 1,
"name": "India International Bank (Malaysia) Berhad",
"updated_at": "2020-03-16 16:27:37"
},
{
"created_at": "2020-03-16 16:27:37",
"deleted_at": null,
"id": 4,
"is_active": 1,
"name": "National Bank of Abu Dhabi Malaysia Berhad",
"updated_at": "2020-03-16 16:27:37"
}
],
"links": {
"first": "https://demo.local/api/banks?page=1",
"last": "https://demo.local/api/banks?page=1",
"next": null,
"prev": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "https://demo.local/api/banks",
"per_page": 5,
"to": 3,
"total": 3
}
}
Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
The exception message explains the issue clearly.
The property 'name' is inside an object which itself placed in an array. So you first decode the array. Then access each object using the index (0..n), then from each object, you can read the 'name' property.
Here you go
class MyData {
final List<Data> data;
MyData({this.data});
factory MyData.fromJson(Map<String, dynamic> json) {
return MyData(
data: json['data'] != null ? (json['data'] as List).map((i) => Data.fromJson(i)).toList() : null,
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
final String created_at;
final String deleted_at;
final int id;
final int is_active;
final String name;
final String updated_at;
Data({this.created_at, this.deleted_at, this.id, this.is_active, this.name, this.updated_at});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
created_at: json['created_at'],
deleted_at: json['deleted_at'],
id: json['id'],
is_active: json['is_active'],
name: json['name'],
updated_at: json['updated_at'],
);
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['created_at'] = this.created_at;
data['id'] = this.id;
data['is_active'] = this.is_active;
data['name'] = this.name;
data['updated_at'] = this.updated_at;
data['deleted_at'] = this.deleted_at;
return data;
}
}
The error makes sense. The 'data' attribute in your JSON is array. So, you'll have to pass index of the item to access 'name' attribute - something like - data['data'][0]['name'] to get 'Maybank'.
Ideally, you should have a class which creates the instance from the JSON. In this case, the code snippet will look like :
Banks banks = new Banks.fromJson(data)
Now, you can use sites like this to create a class definition (including.fromJson).