我在Dart中使用映射器时遇到了问题,这对我来说是个大问题。我需要获取json对象的列表,但是我想处理异常,这就是为什么我将Either类型用作函数的返回值的原因。处理它的唯一方法,但我不确定它是否可以工作在arrayListFromJson(json):
class ItemEntryMapper {
static Either<Exception, ItemEntryModel> fromJson(Map<String, dynamic> json) {
try {
return Right(ItemEntryModel(
id: json['id'] as int,
value: json['value'] as List<String>,
hasError: json['hasError'] as bool,
file: FileWrapperMapper.arrayListFromJson(json['file']).fold(
(Exception exception) => null,
(List<FileWrapperModel> fileWrappers) => fileWrappers),
hasEntryTable: json['hasEntryTable'] as bool,
type: json['type'] as int,
audit: arrayListFromJson(json['audit']).fold(
(Exception exception) => null,
(List<ItemEntryModel> itemEntries) => itemEntries),
auditParentId: json['auditParentId'] as int,
errorFieldName: json['errorFieldName'] as String,
blueAppLaunch:
json['blueAppLaunch'] as List<WorkflowBlueAppLaunchModel>,
workflowBlueAppLaunch:
json['workflowBlueAppLaunch'] as WorkflowBlueAppLaunchModel,
parentWordId: json['parentWordId'] as int,
));
} catch (e) {
return Left(Exception('An error during ItemEntry mapping : $e'));
}
}
static Either<Exception, List<ItemEntryModel>> arrayListFromJson(
Map<String, dynamic> json) {
final list = List<ItemEntryModel>();
final List<dynamic> itemEntries = json['file'];
var result = itemEntries.map((dynamic e) => fromJson(e)).toList();
result.forEach((e) => e.fold(
(Exception exception) => Left<Exception, List<ItemEntryModel>>(
Exception('An error during ItemEntries mapping : $e')),
e.fold((Exception exception) => null, (ItemEntryModel itemEntry) {
list.add(itemEntry);
})));
return Right(list);
}
}
这很奇怪。我必须使用一个foreach,然后在foreach中使用一个折叠,在第二个参数中打开一个新的折叠...您知道如何提高它的效率(实际上确实很丑)?可能是因为我暂时不熟悉这种语言。
整个块仅用于获取列表和处理错误。...谢谢
尝试一下
List<YourModel> _jsonArrayToList(List list) {
List<YourModel> _list = [];
for (var i = 0; i < list.length; i++) {
_list.add(YourModel.fromJson(list[i]));
}
return _list;}