如何正确使用来自 Json 映射器的列表并处理异常?

How to work properly with list from Json mapper and handle exception?

我在 Dart 中遇到映射器问题,这对我来说是个大问题。我需要获取 json 对象的列表,但我想处理异常,这就是为什么我使用 Either 类型作为我的函数的 return 的原因。处理它的唯一方法,我不确定它是否可以工作是在 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;}