在 Dart 中解析没有名称的 json 数组
Parse json array without names in Dart
我无法解析这样的 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 我也通过这个网站做了一些研究,发现了一些非常相似但有点不同的问题,这对我没有帮助。
因为这是一个数组而不仅仅是一个 JSON 你需要做这样的事情:
mList = List<UserModel>.from(response.data.map((i) => UserModel.fromJson(i)));
提示:要使用 toJson 和 fromJson 生成模型,请使用此网站:
https://javiercbk.github.io/json_to_dart/
我无法解析这样的 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 我也通过这个网站做了一些研究,发现了一些非常相似但有点不同的问题,这对我没有帮助。
因为这是一个数组而不仅仅是一个 JSON 你需要做这样的事情:
mList = List<UserModel>.from(response.data.map((i) => UserModel.fromJson(i)));
提示:要使用 toJson 和 fromJson 生成模型,请使用此网站: https://javiercbk.github.io/json_to_dart/