【发布时间】:2021-09-22 07:55:48
【问题描述】:
我遇到了上述问题,我知道在我的数据中有些内容为空,例如 Diesel 的 leistungData 不包含任何内容,因此标题为空:
"title":"Benzin",
"leistungData":[
{
"title":"240 PS"
}
]
},
{
"title":"Diesel",
"leistungData":[
]
},
所以我知道“Null”不是“String”类型的子类型。但是如何更改下面的代码,以便保留这个 Json 结构?
import 'leistungData.dart';
part 'treibstoffData.g.dart';
@JsonSerializable(explicitToJson: true)
class TreibstoffData {
final String title;
final List <LeistungData> leistungData;
TreibstoffData(this.title, this.leistungData);
factory TreibstoffData.fromJson(Map<String, dynamic> json)
=> _$TreibstoffDataFromJson(json);
Map<String, dynamic> toJson() => _$TreibstoffDataToJson(this);
}
&这里是 LeistungData:
import 'package:json_annotation/json_annotation.dart';
import 'unterscheidungsData.dart';
part 'leistungData.g.dart';
@JsonSerializable()
class LeistungData {
final String title;
LeistungData(this.title);
factory LeistungData.fromJson(Map<String, dynamic> json)
=> _$LeistungDataFromJson(json);
Map<String, dynamic> toJson() => _$LeistungDataToJson(this);
}
我希望我清楚并且没有忘记任何事情,如果我错过了什么就写信给我
【问题讨论】:
-
你也能显示 TreibstoffDataFromJson 方法吗?
-
认为我们现在已修复,但感谢您的意愿)
-
嘿,谢谢你的回答,虽然另一个对我有用,但我喜欢默认值方法,因为你不必使用 ? & !运算符