Parse json array without names in Dart

Issue

I cannot parse such json

[{"operation_id":"38911","external_id":null,"status":"SUCCESS","date":"2019-12-01T12:30:08.000Z","amount":200}]

The problem lies in array with dynamic names. Here’s my POJO:

class PaymentHistoryResponse {
final List<History> list;

PaymentHistoryResponse({this.list});
}

class History {
final String operationId;
final dynamic externalId;
final String status;
final DateTime date;
final int amount;

History({
@required this.operationId,
@required this.externalId,
@required this.status,
@required this.date,
@required this.amount
});

factory History.fromJson(String str) => History.fromMap(json.decode(str));

String toJson() => json.encode(toMap());

factory History.fromMap(Map<String, dynamic> json) => History(
operationId: json["operation_id"],
externalId: json["external_id"],
status: json["status"],
date: DateTime.parse(json["date"]),
amount: json["amount"]
);

Map<String, dynamic> toMap() => {
"operation_id": operationId,
"external_id": externalId,
"status": status,
"date": date.toIso8601String(),
"amount": amount
};
}

I also receive other json containing arrays, but named ones and I was able to decode them. How can I convert this one? P.s I’ve also made some research through this site and found some quite similar questions but a bit different and it didn’t help me.

Solution

Since this is an array and not just a JSON you will need to do something like this:

mList = List<UserModel>.from(response.data.map((i) => UserModel.fromJson(i)));

Hint: for generating models with toJson and fromJson use this website:
https://javiercbk.github.io/json_to_dart/

Answered By – Karim

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.