I have Json uploaded on a conditional server, I access this server via Dio:
Future getDataDio() async {
try {
final Dio dio = Dio();
final response = await dio
.get('https://run.mocky.io/v3/26681b8c-6581-4b8b-8fbe-3da2dc7bb785');
return HystoryOperations.fromJson(response.data);
} on DioError catch (e) {
print('error log: ${e.error}');
}
}
Json example I’m referring to:
{
"transaction_556505":{
"date" : "14.01.2022 г.",
"time" : "00:52",
"sum" : 351.05,
"id_order" : 556505,
"status_order" : "paid",
"type_order" : "payment_in"
},
"transaction_556329":{
"date" : "14.01.2022 г.",
"time" : "00:59",
"sum" : 1222.96,
"id_order" : 556329,
"status_order" : "payment_not_completed",
"type_order" : "payment_in"
},
"transaction_555111":{
"date" : "13.01.2022 г.",
"time" : "15:11",
"sum" : 512.71,
"id_order" : 555111,
"status_order" : "in_processing",
"type_order" : "payment_in"
}
}
Json serialization has been written, in which an exception appears due to the fact that all keys in the Json request are unique:
@JsonSerializable(explicitToJson: true)
class HystoryOperations {
final Map<String, dynamic> transaction;
HystoryOperations({required this.transaction});
factory HystoryOperations.fromJson(Map<String, dynamic> json) =>
_$HystoryOperationsFromJson(json);
Map<String, dynamic> toJson() => _$HystoryOperationsToJson(this);
}
// GENERATED CODE
HystoryOperations _$HystoryOperationsFromJson(Map<String, dynamic> json) =>
HystoryOperations(
transaction: json['transaction'] as Map<String, dynamic>, //Exception has occurred. _CastError (type 'Null' is not a subtype of type 'Map<String, dynamic>' in type cast)
);
Map<String, dynamic> _$HystoryOperationsToJson(HystoryOperations instance) =>
<String, dynamic>{
'transaction': instance.transaction,
};
2
Answers
Thanks @Prashant
Fixed the JSON request:
and serialization with access to JSON via dio:
Its easy.
You have to make two model classes.
One for List of Transactions and one for Individual transactions.
Then you can easily Get all the items from this type of JSON.
Your first Model Class should look like:
And Your second Model Class looks like this.
What happening here is :-
We are adding all keys inside a List of String named as "listOfTransactionNames " and then finding all Individual Transactions using those keys.
After that we are using from Json method of second class to add all single values in the list of "listOfTransaction" which are found by keys inside "listOfTransactionNames".