我正在尝试从flutter中的服务器获取数据,并且我正在为我的数据模型使用json_serializable。我成功地获取了数据,但当需要转换数据列表中的json时,我会收到以下错误:未处理的异常:类型"Null"不是类型转换中类型"String"的子类型。我不知道该怎么解决。这是我的提取功能
Future<List<Data>> getallNews() async {
try {
var response = await NewsAppApi.dio.get(ALL_NEWS);
// If the server did return a 200 OK response,
// then parse the JSON.
List parsed = response.data['data'];
List<Data> _news = [];
parsed.forEach((element) {
print(element);
Data n = Data.fromJson(element);
print(n);
_news.add(n);
});
//List<Data> _news = parsed.map((json) => Data.fromJson(json)).toList();
return _news;
} on DioError catch (e) {
throw showNetworkError(e);
}
}
这是我的型号
@JsonSerializable(explicitToJson: true)
class Data {
final int id;
final int author;
final String title;
final String body;
final String link;
final DateTime? datePublished;
final DateTime dateTobePublished;
final int published;
final int tobePublished;
final int status;
final DateTime? deletedAt;
final DateTime createdAt;
final DateTime updatedAt;
final List<Tags> tags;
Data(
{
required this.id,
required this.author,
required this.title,
required this.body,
required this.link,
required this.datePublished,
required this.dateTobePublished,
required this.published,
required this.tobePublished,
required this.status,
required this.deletedAt,
required this.createdAt,
required this.updatedAt,
required this.tags});
factory Data.fromJson(Map<String, dynamic> json) => _$DataFromJson(json);
Map<String, dynamic> toJson() => _$DataToJson(this);
}
这是我从服务器得到的数据
{
"data": [
{
"id": 105,
"author": 1,
"title": "testLaura",
"body": "asdadsdas",
"link": "https://www.google.com/",
"datePublished": null,
"dateTobePublished": "2021-03-09 22:51:00",
"published": 0,
"tobePublished": 1,
"status": 0,
"deleted_at": null,
"created_at": "2021-03-09T08:18:02.000000Z",
"updated_at": "2021-03-09T08:18:02.000000Z",
"tags": [
{
"id": 4,
"title": "Studenti"
}
]
},
{
"id": 104,
"author": 8,
"title": "news",
"body": "sdadasdasasdasddasads",
"link": "https://www.google.com/",
"datePublished": null,
"dateTobePublished": "2021-03-09 08:11:20",
"published": 0,
"tobePublished": 1,
"status": 0,
"deleted_at": null,
"created_at": "2021-03-09T08:12:36.000000Z",
"updated_at": "2021-03-09T08:12:36.000000Z",
"tags": [
{
"id": 2,
"title": "Genitori"
}
]
},
感谢的帮助
感谢大家的帮助,我知道错误是在解析数据的部分发生的,但它与可为null的数据(由包自动生成的代码处理(无关,而是因为我忘记重命名数据模型中的键,例如:
@JsonKey(name: 'deleted_at')
final DateTime? deletedAt;
这就是为什么空错误
错误很可能发生在DateTime
字段中,因为它是数据中唯一显示null
的字段,而DateTime.parse()
要求值不为null。这些字段可能导致错误:
// These fields are causing the error
final DateTime? datePublished;
final DateTime? deletedAt;
// Other fields that could bring the error as well
final DateTime dateTobePublished;
final DateTime createdAt;
final DateTime updatedAt;
在解析它们之前进行检查,例如使用字段datePublished
:
...
datePublished: (datePublished != null) ? DateTime.parse(datePublished) : null;
...
您需要考虑在发布日期和删除日期中收到的空值。你理解你发布的代码吗?错误的原因是什么?
在将json映射转换为类时,会出现错误。