我有一个json对象,其中包括一个对象,可以是null。这是我的json:
I/flutter (23570): ║ {
I/flutter (23570): ║ elements: [
I/flutter (23570): ║ {
I/flutter (23570): ║ id: 1,
I/flutter (23570): ║ name: "a1",
I/flutter (23570): ║ owner: {firstName: امین, lastName: جمالی, mobile: 9014523821}
I/flutter (23570): ║ },
I/flutter (23570): ║ {id: 2, name: a2}
I/flutter (23570): ║ ],
I/flutter (23570): ║ totalElements: 2
I/flutter (23570): ║ }
owner在第一个元素中有数据,在第二个元素中为空。这是我的视图模型:
class UnitItemViewModel {
final int id;
final String name;
UnitOwner? owner;
UnitItemViewModel({
required this.id,
required this.name,
this.owner,
});
factory UnitItemViewModel.fromJson(final Map<String, dynamic> json) =>
UnitItemViewModel(
id: json['id'],
name: json['name'],
owner: UnitOwner.fromJson(json['owner']),
);
}
class UnitOwner {
final String firstName, lastName;
final String mobile;
UnitOwner({
required this.firstName,
required this.lastName,
required this.mobile,
});
factory UnitOwner.fromJson(final Map<String, dynamic> json) => UnitOwner(
firstName: json['firstName'],
lastName: json['lastName'],
mobile: json['mobile'],
);
}
解析时,我得到了这个异常:
E/flutter (23570): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception:
NoSuchMethodError: The method '[]' was called on null.
E/flutter (23570): Receiver: null
E/flutter (23570): Tried calling: []("firstName")
,这是我的存储库:
final items = (data['elements'] as List)
.map((final e) => UnitItemViewModel.fromJson(
e as Map<String, dynamic>,
))
.toList();
任何主意都可以。
这一行你会得到错误,因为json
是null
firstName: json['firstName']
你应该这样修改fromJson函数:
factory UnitOwner.fromJson(final Map<String, dynamic>? json) => UnitOwner(
firstName: json?['firstName'] ?? '',
lastName: json?['lastName'] ?? '',
mobile: json?['mobile'] ?? '',
);