【发布时间】:2020-01-25 13:52:58
【问题描述】:
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:NoSuchMethodError:方法 'map' 在 null 上被调用。 E/颤振(19718):接收器:空 E/flutter (19718): 尝试调用: map(Closure: (dynamic) => SeriesNo)
我尝试了 json_annotation 和 json Serieizable 但不起作用。根据我的模型 one.json 是好的。但是 two.json 是请求错误发生为标题。如何解决。我知道系列号是错误但我不知道如何解决。
这是一个.json
{
"bookDetail": {
"title": "aaa",
"author": "aaa",
"image": "https://",
"text": "aaa",
"series_no": [
{
"id": 2
}
],
"created_at": "2019-08-27 15:19:10"
}
}
这是两个.json
{
"bookDetail": {
"title": "Test",
"author": "TEst",
"image": "https:/riv19q9x.png",
"text": "Test",
"series_no": null,
"created_at": "2019-08-27 15:13:56"
}
}
这是使用 bloc Flutter 的 detail.model
class BookDetailModel {
BookDetail bookDetail;
BookDetailModel({
this.bookDetail,
});
factory BookDetailModel.fromJson(Map<String, dynamic> json) =>
new BookDetailModel(
bookDetail: BookDetail.fromJson(json["bookDetail"]),
);
Map<String, dynamic> toJson() => {
"bookDetail": bookDetail.toJson(),
};
}
@JsonSerializable(nullable: true)
class BookDetail {
String title;
String author;
String image;
String text;
List<SeriesNo> seriesNo;
DateTime createdAt;
BookDetail({
this.title,
this.author,
this.image,
this.text,
this.seriesNo,
this.createdAt,
});
factory BookDetail.fromJson(Map<String, dynamic> json) => new BookDetail(
title: json["title"],
author: json["author"],
image: json["image"],
text: json["text"],
seriesNo: new List<SeriesNo>.from(
json["series_no"].map((x) => SeriesNo.fromJson(x))),
createdAt: DateTime.parse(json["created_at"]),
);
Map<String, dynamic> toJson() => {
"title": title,
"author": author,
"image": image,
"text": text,
"series_no": new List<dynamic>.from(seriesNo.map((x) => x.toJson())),
"created_at": createdAt.toIso8601String(),
};
}
@JsonSerializable(nullable: true)
class SeriesNo {
int id;
SeriesNo({
this.id,
});
factory SeriesNo.fromJson(Map<String, dynamic> json) => new SeriesNo(
id: json["id"],
);
Map<String, dynamic> toJson() => {
"id": id,
};
}
【问题讨论】:
-
尝试验证之前是否为空: seriesNo: json["series_no"] != null ?新列表
.from(json["series_no"].map((x) => SeriesNo.fromJson(x))) : List () -
@Stel 你的回答没问题。但是你知道怎么用json注解吗。
-
如何验证json键不存在。第一个系列不存在。
-
我不知道,但也许这个包可以帮助你:pub.dev/packages/json_annotation