【问题标题】:Parse json array without names in Dart在 Dart 中解析没有名称的 json 数组
【发布时间】:2020-03-28 03:28:38
【问题描述】:

我无法解析这样的 json

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

问题在于具有动态名称的数组。这是我的 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
};
}

我还收到了其他包含数组的 json,但命名的数组,我能够解码它们。我怎样才能转换这个? P.s 我也通过这个网站做了一些研究,发现了一些非常相似的问题,但有点不同,这对我没有帮助。

【问题讨论】:

  • 我不知道这里的动态名称是什么。
  • @danypata 看看我的 json。它是一个数组,其中包含一个索引为 0 的对象。如果我们有 14 个对象怎么办?

标签: json flutter dart flutter-layout dart-pub


【解决方案1】:

由于这是一个数组而不仅仅是一个 JSON,您需要执行以下操作:

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

提示:要使用 toJson 和 fromJson 生成模型,请使用此网站: https://javiercbk.github.io/json_to_dart/

【讨论】:

  • 我试过 List.from(response.json().map((i) => PaymentHistoryResponse.fromJson(i))) 并没有帮助。我还通过网络生成器生成了我的 pojo。
  • 非常感谢兄弟救了我的命。爱你
猜你喜欢
  • 2020-08-09
  • 2020-01-08
  • 1970-01-01
  • 2017-06-10
  • 2019-01-29
  • 2019-09-21
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
相关资源
最近更新 更多