【发布时间】:2020-03-11 06:43:17
【问题描述】:
序列化时出现错误。控制台日志说:
> NoSuchMethodError: Class 'String' has no instance method 'forEach'.
> Receiver: "no" Tried calling: forEach(Closure: (dynamic) => Null) dan
> 0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
> 1 new Article.fromJson (package:tribun_travel/model/article.dart:84:19)
> 2 new ResponseRead.fromJson (package:tribun_travel/model/response_read.dart:16:39)
> 3 BlogRepository.readNewsById (package:tribun_travel/repositories/blog_repository.dart:21:25)
> <asynchronous suspension>
> 4 BlogBloc.mapEventToState (package:tribun_travel/bloc/blog_bloc.dart:28:61) <asynchronous
> suspension>
我所做的是,我想将 json 序列化为 Dart 中的 Object。在我的班级里面有列表对象。 sn-p 代码如下:
class ResponseRead {
String status;
String message;
String source;
Article data;
ResponseRead({this.status, this.message, this.source, this.data});
ResponseRead.fromJson(Map<String, dynamic> json) {
status = json['status'];
message = json['message'];
source = json['source'];
data = json['data'] != null ? new Article.fromJson(json['data']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['status'] = this.status;
data['message'] = this.message;
data['source'] = this.source;
if (this.data != null) {
data['data'] = this.data.toJson();
}
return data;
}
}
class Article{
String id;
String fulltexts;
List<Tag> tag;
List<Related> related;
Article(
{this.id,
this.fulltexts,
this.tag,
this.related
});
Article.fromJson(Map<String, dynamic> json) {
id = json['id'];
fulltexts = json['fulltexts'];
if (json['tag'] != null) {
tag = new List<Tag>();
json['tag'].forEach((v) {
tag.add(new Tag.fromJson(v));
});
}
if (json['related'] != null) {
related = new List<Related>();
json['related'].forEach((v) {
related.add(new Related.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['fulltexts'] = this.fulltexts;
if (this.tag != null) {
data['tag'] = this.tag.map((v) => v.toJson()).toList();
}
if (this.related != null) {
data['related'] = this.related.map((v) => v.toJson()).toList();
}
return data;
}
@override
String toString() {
return 'Article{id: $id, title: $title, photo: $photo}';
}
}
我认为我的服务没有问题,因为它返回了我想要的。 但是,为什么我在序列化的时候还是报错呢?
更新 这是我的示例 Json 文件
{
"status": "success",
"message": "Found",
"source": "memcached",
"article": {
"title": "Ini Alasan Pramugari Jarang Sakit Meski Terbang Berjam-jam",
"fulltexts": "<p><</p>",
"tag": [
{
"id": "1",
"title": "a",
"alias": "a"
},
{
"id": "2",
"title": "b",
"alias": "b"
}
],
"related": [
{
"id": "79224",
},
{
"id": "79219",
}
]
}
}
【问题讨论】:
-
发布您的输入 JSON
-
我已经更新了问题
-
嗯,看起来不错,在
if (json['tag'] != null) {之后添加print(json['tag'])在if (json['related'] != null) {内执行相同操作 -
我输入了
print('apa itu TAG ${json['tag']}');并打印了flutter: apa itu TAG no -
所以它不是你的 JSON - 在
Article.fromJsonctor 中添加print(json)
标签: android flutter serialization dart