Related
I'm getting an exception when trying to get the data from the API. When there's data in the response it works perfectly, but if the response is empty it throws this exception. Does anyone know how to handle this?
This is how the response looks like-
When there's data:
When it's empty:
The exception I'm getting:
My model class:
import 'dart:convert';
TransactionsList transactionsListFromJson(String str) {
final jsonData = json.decode(str);
return TransactionsList.fromJson(jsonData);
}
String transactionsListToJson(TransactionsList data) {
final dyn = data.toJson();
return json.encode(dyn);
}
class TransactionsList {
String? type;
String? message;
int? paidTotalRecords;
PaidTotalAmount? paidTotalAmount;
List<PaidRecordDatum>? paidRecordData;
TransactionsList(
{this.type,
this.message,
this.paidTotalRecords,
this.paidTotalAmount,
this.paidRecordData});
factory TransactionsList.fromJson(Map<String, dynamic> json) =>
TransactionsList(
type: json["type"],
message: json["message"],
paidTotalRecords: json["paid_TotalRecords"],
paidTotalAmount: PaidTotalAmount.fromJson(json["paid_TotalAmount"]),
paidRecordData: List<PaidRecordDatum>.from(
json["paid_recordData"].map((x) => PaidRecordDatum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"type": type,
"message": message,
"paid_TotalRecords": paidTotalRecords,
"paid_TotalAmount": paidTotalAmount!.toJson(),
"paid_recordData":
List<dynamic>.from(paidRecordData!.map((x) => x.toJson())),
};
}
class PaidRecordDatum {
int? tcid;
String? crn;
String? reqCurrency;
String? reqAmount;
String? paidCurrency;
String? paidAmount;
String? createdAt;
String? fromName;
String? toName;
String? toEmail;
String? type;
String? typeNote;
PaidRecordDatum({
this.tcid,
this.crn,
this.reqCurrency,
this.reqAmount,
this.paidCurrency,
this.paidAmount,
this.createdAt,
this.fromName,
this.toName,
this.toEmail,
this.type,
this.typeNote,
});
factory PaidRecordDatum.fromJson(Map<String, dynamic> json) =>
PaidRecordDatum(
tcid: json["tcid"],
crn: json["CRN"],
reqCurrency: json["req_currency"],
reqAmount: json["req_amount"],
paidCurrency: json["paid_currency"],
paidAmount: json["paid_amount"],
createdAt: json["created_at"],
fromName: json["from_name"],
toName: json["to_name"],
toEmail: json["to_email"],
type: json["type"],
typeNote: json["type_note"],
);
Map<String, dynamic> toJson() => {
"tcid": tcid,
"CRN": crn,
"req_currency": reqCurrency,
"req_amount": reqAmount,
"paid_currency": paidCurrency,
"paid_amount": paidAmount,
"created_at": createdAt,
"from_name": fromName,
"to_name": toName,
"to_email": toEmail,
"type": type,
"type_note": typeNote,
};
}
class PaidTotalAmount {
String? lkr;
PaidTotalAmount({
this.lkr,
});
factory PaidTotalAmount.fromJson(Map<String, dynamic> json) =>
PaidTotalAmount(
lkr: json["LKR"],
);
Map<String, dynamic> toJson() => {
"LKR": lkr,
};
}
The issue is your PaidTotalAmount is list when it is empty but when it have data it use List DataType. You can ask your backend to fix it and make single data type. You can also tweak on runtime, I am returning null when it is empty
paidTotalAmount: () {
try {
return PaidTotalAmount.fromJson(json["paid_TotalAmount"]);
} catch (e) {
log(e.toString());
}
}(),
im using this json response to convert it to an object
json response
{"Data":"{\"IdToken\":\"eyJraWQiOiJxazZwYk9GZVdPWnRTbWorczlqMng2cDN5bUFUcXdDTlhMQ09Ic1JIOFNFPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIyMmEwZjViMi03NTY3LTQwODQtYjUzYS0zMzhjNTE5NmNiYWQiLCJjb2duaXRvOmdyb3VwcyI6WyJCdXNpbmVzc19EZXZlbG9wbWVudF9SZWFkT25seSIsIk9wZXJhdGlvbl9MZXZlbF8xX1JlYWRPbmx5IiwiQnVzaW5lc3NfRGV2ZWxvcG1lbnRfTGV2ZWxfMyIsIkZhY2lsaXR5X1N0YWZmX01lbWJlciIsIk9wZXJhdGlvbl9MZXZlbF8zIiwiTWVtYmVyIiwiRmluYW5jZV9MZXZlbF8zIiwiRmluYW5jZV9MZXZlbF8yIiwiT3BlcmF0aW9uX0xldmVsXzEiLCJCdXNpbmVzc19EZXZlbG9wbWVudF9MZXZlbF8xIiwiQnVzaW5lc3NfRGV2ZWxvcG1lbnRfTGV2ZWxfMiIsIlByaXZpbGVnZWRfUmVwb3J0c19BY2Nlc3MiLCJ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TOCUs7RAyg3eVMNMDJWuH598Sew5Vf7nK.cYy20EQngV7xyTsUBWHy0g\"}","Name":null,"Message":null,"WaitInSeconds":0,"Success":true,"Errors":[],"ErrorNumber":0}
model class
import 'dart:convert';
JwtTokenResponseModel jwtTokenResponseModelFromJson(String str) =>
JwtTokenResponseModel.fromJson(json.decode(str));
String jwtTokenResponseModelToJson(JwtTokenResponseModel data) =>
json.encode(data.toJson());
class JwtTokenResponseModel {
JwtTokenResponseModel({
this.data,
this.name,
this.message,
this.waitInSeconds,
this.success,
this.errors,
this.errorNumber,
});
Data? data;
String? name;
String? message;
int? waitInSeconds;
bool? success;
List<dynamic>? errors;
int? errorNumber;
factory JwtTokenResponseModel.fromJson(Map<String, dynamic> json) =>
JwtTokenResponseModel(
data: Data.fromJson(json["Data"]),
name: json["Name"],
message: json["Message"],
waitInSeconds: json["WaitInSeconds"],
success: json["Success"],
errors: List<dynamic>.from(json["Errors"].map((x) => x)),
errorNumber: json["ErrorNumber"],
);
Map<String, dynamic> toJson() => {
"Data": data!.toJson(),
"Name": name,
"Message": message,
"WaitInSeconds": waitInSeconds,
"Success": success,
"Errors": List<dynamic>.from(errors!.map((x) => x)),
"ErrorNumber": errorNumber,
};
#override
String toString() {
return toJson().toString();
}
}
class Data {
Data({
this.idToken,
this.accessToken,
this.refreshToken,
});
String? idToken;
String? accessToken;
String? refreshToken;
factory Data.fromJson(Map<String, dynamic> json) => Data(
idToken: json["IdToken"],
accessToken: json["AccessToken"],
refreshToken: json["RefreshToken"],
);
Map<String, dynamic> toJson() => {
"IdToken": idToken,
"AccessToken": accessToken,
"RefreshToken": refreshToken,
};
#override
String toString() {
return toJson().toString();
}
}
When calling the converter here
final converted = json.decode(res);
return JwtTokenResponseModel.fromJson(converted);
I get the error String is not a subtype of Map<String, dynamic>.
how can I rectify this error.
any help is welcome heartedly.
this line causes the error I might say " data: Data.fromJson(json["Data"]),"
replace it by Data.fromJson( json.decode(json["Data"]))
to check if it's really the line causes the issue print it a see if it's a string or map
i have a factory to convert a json file to a class
Map<String, dynamic>? tokenProperties;
factory Token.fromJson(Map<String, dynamic> map) {
return Token(
tokenProperties: map['properties']
);
}
i receive in "map" param (keys are dynamics, never the same keys and values.)
when i want to affect the value tokenProperties: map['properties']
i don't why but the quote disappear... see the exception:
The full class:
// Dart imports:
import 'dart:convert';
/// SPDX-License-Identifier: AGPL-3.0-or-later
// To parse this JSON data, do
//
// final token = tokenFromJson(jsonString);
Token tokenFromJson(String str) => Token.fromJson(json.decode(str));
String tokenToJson(Token data) => jsonEncode(data.toJson());
String tokenToJsonForTxDataContent(Token data) {
return jsonEncode(data.toJsonForTxDataContent());
}
class Token {
Token(
{this.address,
this.genesis,
this.name,
this.id,
this.supply,
this.type,
this.symbol,
this.tokenProperties});
String? address;
String? genesis;
String? name;
String? id;
int? supply;
String? type;
String? symbol;
Map<String, dynamic>? tokenProperties;
factory Token.fromJson(Map<String, dynamic> map) {
return Token(
address: map['address'],
genesis: map['genesis'],
name: map['name'],
id: map['id'],
supply: map['supply'] == null
? null
: int.tryParse(map['supply'].toString()),
type: map['type'],
symbol: map['symbol'],
tokenProperties: map['properties']);
}
Map<String, dynamic> toJson() => <String, dynamic>{
'address': address,
'genesis': genesis,
'name': name,
'id': id,
'supply': supply,
'type': type,
'symbol': symbol,
'properties': tokenProperties,
};
Map<String, dynamic> toJsonForTxDataContent() => <String, dynamic>{
'name': name,
'supply': supply,
'type': type,
'symbol': symbol,
'properties': tokenProperties,
};
}
I'm having trouble with jsonEncode even though I've done this multiple times and followed the documentation (Link). I'm not seeing what is wrong.
import 'package:json_annotation/json_annotation.dart';
part 'block.g.dart';
#JsonSerializable()
class Block {
Block(
this.name,
this.required,
this.type,
this.stringValue,
this.checkboxValue,
this.numericValue,
this.minNumericRestraint,
this.maxNumericRestraint
);
String name;
bool required;
String type;
String stringValue;
bool checkboxValue;
double numericValue;
double minNumericRestraint;
double maxNumericRestraint;
factory Block.fromJson(Map<String, dynamic> json) => _$BlockFromJson(json);
Map<String, dynamic> toJson() => _$BlockToJson(this);
}
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'block.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Block _$BlockFromJson(Map<String, dynamic> json) => Block(
json['name'] as String,
json['required'] as bool,
json['type'] as String,
json['stringValue'] as String,
json['checkboxValue'] as bool,
(json['numericValue'] as num).toDouble(),
(json['minNumericRestraint'] as num).toDouble(),
(json['maxNumericRestraint'] as num).toDouble(),
);
Map<String, dynamic> _$BlockToJson(Block instance) => <String, dynamic>{
'name': instance.name,
'required': instance.required,
'type': instance.type,
'stringValue': instance.stringValue,
'checkboxValue': instance.checkboxValue,
'numericValue': instance.numericValue,
'minNumericRestraint': instance.minNumericRestraint,
'maxNumericRestraint': instance.maxNumericRestraint,
}
Calling jsonEncode(Block(...)); results in following error: Error: Converting object to an encodable object failed: Instance of 'Block'
I reran the build script multiple times, wrote the toJson() method manually and invalidated my Android Studio cache.
hello everyone I'm trying to fetch JSON from API, but I'm getting this error while mapping the JSON into the model I created it type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
this is the JSON response
{"data":{"userinfo":[{"firstname":"MAEN","lastname":"NASSAN","email":"maen.alnassan#outlook.com","active_status":0,"dark_mode":0,"messenger_color":"#2180f3","avatar":"avatar.png","gender":"male","region":"Turkey","birthyear":"2021","birthday":"1","birthmonth":"January","phonenumber":53105311,"category":"0","profilestatus":"private","ban":"0","banReason":"0","banDurationByDays":"0","email_verified_at":null,"created_at":"2021-05-24T16:27:52.000000Z","updated_at":"2021-05-24T16:27:52.000000Z"}],"userfriendsPosts":[{"postid":1,"userid":3,"posttitle":"Post 1 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:49:48.000000Z","updated_at":"2021-05-22T20:49:48.000000Z"},{"postid":3,"userid":3,"posttitle":"Post 2 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:58:40.000000Z","updated_at":"2021-05-22T20:58:40.000000Z"},{"postid":4,"userid":3,"posttitle":"Post 3 mohamed","post":"noattachment","likesCounter":0,"commentsCounter":0,"category":"0","created_at":"2021-05-22T20:58:43.000000Z","updated_at":"2021-05-22T20:58:43.000000Z"}],"usernotifications":[],"userlikes":[]}}
and this is the Model Class
import 'dart:convert';
Data dataFromJson(String str) => Data.fromJson(json.decode(str));
String dataToJson(Data data) => json.encode(data.toJson());
class Data {
Data({
this.data,
});
DataClass data;
factory Data.fromJson(Map<String, dynamic> json) => Data(
data: DataClass.fromJson(json["data"]),
);
Map<String, dynamic> toJson() => {
"data": data.toJson(),
};
}
class DataClass {
DataClass({
this.userinfo,
this.userfriendsPosts,
this.usernotifications,
this.userlikes,
});
List<Userinfo> userinfo;
List<UserfriendsPost> userfriendsPosts;
List<dynamic> usernotifications;
List<dynamic> userlikes;
factory DataClass.fromJson(Map<String, dynamic> json) => DataClass(
userinfo: List<Userinfo>.from(json["userinfo"].map((x) => Userinfo.fromJson(x))),
userfriendsPosts: List<UserfriendsPost>.from(json["userfriendsPosts"].map((x) => UserfriendsPost.fromJson(x))),
usernotifications: List<dynamic>.from(json["usernotifications"].map((x) => x)),
userlikes: List<dynamic>.from(json["userlikes"].map((x) => x)),
);
Map<String, dynamic> toJson() => {
"userinfo": List<dynamic>.from(userinfo.map((x) => x.toJson())),
"userfriendsPosts": List<dynamic>.from(userfriendsPosts.map((x) => x.toJson())),
"usernotifications": List<dynamic>.from(usernotifications.map((x) => x)),
"userlikes": List<dynamic>.from(userlikes.map((x) => x)),
};
}
class UserfriendsPost {
UserfriendsPost({
this.postid,
this.userid,
this.posttitle,
this.post,
this.likesCounter,
this.commentsCounter,
this.category,
this.createdAt,
this.updatedAt,
});
int postid;
int userid;
String posttitle;
String post;
int likesCounter;
int commentsCounter;
String category;
DateTime createdAt;
DateTime updatedAt;
factory UserfriendsPost.fromJson(Map<String, dynamic> json) => UserfriendsPost(
postid: json["postid"],
userid: json["userid"],
posttitle: json["posttitle"],
post: json["post"],
likesCounter: json["likesCounter"],
commentsCounter: json["commentsCounter"],
category: json["category"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"postid": postid,
"userid": userid,
"posttitle": posttitle,
"post": post,
"likesCounter": likesCounter,
"commentsCounter": commentsCounter,
"category": category,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
class Userinfo {
Userinfo({
this.firstname,
this.lastname,
this.email,
this.activeStatus,
this.darkMode,
this.messengerColor,
this.avatar,
this.gender,
this.region,
this.birthyear,
this.birthday,
this.birthmonth,
this.phonenumber,
this.category,
this.profilestatus,
this.ban,
this.banReason,
this.banDurationByDays,
this.emailVerifiedAt,
this.createdAt,
this.updatedAt,
});
String firstname;
String lastname;
String email;
int activeStatus;
int darkMode;
String messengerColor;
String avatar;
String gender;
String region;
String birthyear;
String birthday;
String birthmonth;
int phonenumber;
String category;
String profilestatus;
String ban;
String banReason;
String banDurationByDays;
dynamic emailVerifiedAt;
DateTime createdAt;
DateTime updatedAt;
factory Userinfo.fromJson(Map<String, dynamic> json) => Userinfo(
firstname: json["firstname"],
lastname: json["lastname"],
email: json["email"],
activeStatus: json["active_status"],
darkMode: json["dark_mode"],
messengerColor: json["messenger_color"],
avatar: json["avatar"],
gender: json["gender"],
region: json["region"],
birthyear: json["birthyear"],
birthday: json["birthday"],
birthmonth: json["birthmonth"],
phonenumber: json["phonenumber"],
category: json["category"],
profilestatus: json["profilestatus"],
ban: json["ban"],
banReason: json["banReason"],
banDurationByDays: json["banDurationByDays"],
emailVerifiedAt: json["email_verified_at"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"firstname": firstname,
"lastname": lastname,
"email": email,
"active_status": activeStatus,
"dark_mode": darkMode,
"messenger_color": messengerColor,
"avatar": avatar,
"gender": gender,
"region": region,
"birthyear": birthyear,
"birthday": birthday,
"birthmonth": birthmonth,
"phonenumber": phonenumber,
"category": category,
"profilestatus": profilestatus,
"ban": ban,
"banReason": banReason,
"banDurationByDays": banDurationByDays,
"email_verified_at": emailVerifiedAt,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
and this is the API request function
static Future<List<Data>> getData(token) async{
Dio dio = new Dio();
dio.options.headers["Authorization"] = "bearer $token";
dio.options.headers["Content-Type"] = 'application/json';
dio.options.headers["Accept"] = 'application/json';
await dio.get(url,).then((response) {
final List<Data> _data = dataFromJson(response.data) as List<Data>;
return _data;
}
).catchError((error) => print(error));
}
I tried all the method to fetch the data and the complex JSON List but it's always ending withe errors looks like this errors
The error you're getting is telling you: "your code expects a String, but you gave it a _InternalLinkedHashMap<String, dynamic> (i.e. a Map<String, dynamic>)".
It's not clear where the error is happening, but my guess is that response.data is a Map<String, dynamic>, but dataFromJson expects a String, and this line is causing the error.
If you look at the docs for Dio.get() (https://pub.dev/documentation/dio/latest/dio/Dio/get.html),
you can see the signature is:
Future<Response<T>> get<T>(String path, { ... });
When you call dio.get(url) without passing a type parameter, it defaults to dynamic, which essentially turns off type-checking. If you expect your api to return a String, you can provide that to dio by using: dio.get<String>(url).
However, if you're immediately going to jsonDecode it, you could modify dataFromJson to accept a Map<String, dynamic> rather than a String, and skip the jsonDecode step.
Finally, I'd recommend you to check out a json library (json_serializable is very easy to get started with). Hand writing json serialization code is repetitive and error-prone. Instead of manually writing your toJson() and fromJson() functions, you simply define stubs, and you can generate serialization code at compile time.
https://pub.dev/packages/json_serializable