0

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.

2
  • I can't figure out which are the dynamic names here. Commented Dec 3, 2019 at 12:33
  • @danypata look at my json. It's an array which contains one object under index 0. What if we have 14 objects? Commented Dec 3, 2019 at 12:35

1 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

1 Comment

I tried List<PaymentHistoryResponse>.from(response.json().map((i) => PaymentHistoryResponse.fromJson(i))) and it didn't help. I also generated my pojo through web generator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.