【发布时间】:2023-03-08 02:07:01
【问题描述】:
我正在尝试从 Dart/Flutter 应用程序中的 Rest API 解析数据。
JSON 在根处包含一个名为 data 的字段,其中包含单词列表。
我想从这个 JSON 中得到一个List<ArticalList>,给出json["data"].map((x) => ArticalList.fromJson(x))
我已经有以下代码:
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.code,
required this.status,
required this.message,
required this.data,
});
final int code;
final String status;
final String message;
final List<ArticalList> data;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
code: json["code"] ?? 0,
status: json["status"] ?? '',
message: json["message"] ?? '',
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class ArticalList {
ArticalList({
required this.id,
required this.title,
required this.detail,
required this.image,
});
int id;
String title;
String detail;
String image;
factory ArticalList.fromJson(Map<String, dynamic> json) => ArticalList(
id: json["id"] == null ? 0 : json["id"],
title: json["title"] == null ? '' : json["title"],
detail: json["detail"] == null ? '' : json["detail"],
image: json["image"] ?? 'http://eduteksolutions.in/images/logo.jpeg',
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"detail": detail == null ? null : detail,
"image": image,
};
}
【问题讨论】:
-
你能告诉我们上面代码中抛出错误的那一行吗?哪个地图函数抛出错误?
-
你能提供你要解析的json吗
-
数据:列表
.from( json["data"].map((x) => ArticalList.fromJson(x))), ); -
data:json["data"]==null?[]: List
.from( json["data"].map((x) => ArticalList.fromJson(x) )),我检查 null 但仍然返回 Data List is Empty
标签: json flutter rest dictionary dart