我正在尝试从服务器中获取数据,并且我正在使用 json_serializable 作为我的数据模型。我成功获取了数据,但是当需要在数据列表中转换 json 时,我收到此错误:未处理的异常:类型“Null”不是类型转换中“字符串”类型的子类型。我不知道怎么解决。这是我的获取功能
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"
}
]
},
谢谢您的帮助