如何解决toJson 无法正常工作 json 序列化程序未处理的异常:无效的参数:“DietModel”的实例
我正在尝试将数据保存在 firestore 上,但在保存到 toJson 时出错。我创建了两个模型diet-model 和TargetModel 来使用json_serializable: ^4.0.0 和json_annotation: ^4.0.0 存储在firestore 上。 TargetModel 有饮食模型列表。错误是运行时错误
错误:
Unhandled Exception: Invalid argument: Instance of 'DietModel'
[ ] E/flutter (23502): #0 convertPlatformException (package:cloud_firestore_platform_interface/src/method_channel/utils/exception.dart:13:5)
[ ] E/flutter (23502): #1 MethodChannelDocumentReference.set (package:cloud_firestore_platform_interface/src/method_channel/method_channel_document_reference.dart:43:13)
[ ] E/flutter (23502): <asynchronous suspension>
[ ] E/flutter (23502): #2 DietPageRepositoryImpl.setTarget (package:dance/services/firestore/firestore-impl/diet-page-repository-impl.dart:31:5)
[ ] E/flutter (23502): <asynchronous suspension>
[ ] E/flutter (23502): #3 DietPageViewModel.setTargetedModel (package:dance/viewmodels/diet-page-view-model/diet-page-view-model.dart:120:5)
[ ] E/flutter (23502): <asynchronous suspension>
import 'package:dance/models/diet-model/diet-model.dart';
import 'package:json_annotation/json_annotation.dart';
part 'targeted-model.g.dart';
@JsonSerializable()
class TargetedModel {
List<DietModel> targetedBreakfast;
List<DietModel> targetedLunch;
List<DietModel> targetedSnacks;
List<DietModel> targetedDinner;
TargetedModel(this.targetedBreakfast,this.targetedLunch,this.targetedSnacks,this.targetedDinner);
factory TargetedModel.fromJson(Map<String,dynamic> json) =>
_$TargetedModelFromJson(json);
Map<String,dynamic> toJson() => _$TargetedModelToJson(this);
}
import 'package:json_annotation/json_annotation.dart';
part 'diet-model.g.dart';
@JsonSerializable()
class DietModel {
int calories;
String name;
int carbs;
int fat;
int protein;
bool selected;
int quantity;
String imageUrl;
DietModel();
factory DietModel.fromJson(Map<String,dynamic> json) =>
_$DietModelFromJson(json);
Map<String,dynamic> toJson() => _$DietModelToJson(this);
}
Future<void> setTarget(DateTime date,TargetedModel model) async {
await _collectionReferenceTD.doc("$date").set(model.toJson()); // getting error here
}
解决方法
添加
@JsonSerializable(explicitToJson: true)
这允许嵌套对象被序列化
此外,您可能还想更新 DietModel 构造函数:
DietModel({this.calories,this.name...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。