我该如何处理飞镖投掷问题?

时间:2019-02-02 06:49:17

标签: json casting dart flutter

我必须作出JSON数据到我的自定义对象,以下代码所示我的模型。

import 'package:meta/meta.dart';

class KakaoMLModel {
  final List<List<double>> jaw;
  final List<List<double>> rightEyebrow;
  final List<List<double>> leftEyebrow;
  final List<List<double>> nose;
  final List<List<double>> rightEye;
  final List<List<double>> leftEye;
  final List<List<double>> lip;

  KakaoMLModel({
    @required this.jaw,
    @required this.rightEyebrow,
    @required this.leftEyebrow,
    @required this.nose,
    @required this.rightEye,
    @required this.leftEye,
    @required this.lip
  });

  factory KakaoMLModel.fromJson(Map<String,dynamic> json) {
    print(json['jaw']);
    return KakaoMLModel(
      jaw: json['jaw'],
      rightEyebrow: json['rightEyebrow'],
      leftEyebrow: json['leftEyebrow'],
      nose: json['nose'],
      rightEye: json['rightEye'],
      leftEye: json['leftEye'],
      lip: json['lip']
    );
  }
}

但是,当我路过参数JSON数据,它发生错误信息是这样的。

_TypeError (type 'List<dynamic>' is not a subtype of type 'List<List<double>>'

json['jaw']格式是象下面

  

[[0.04616761798553884,0.5475042080412023],[0.026029605771987013,   0.6203330820534684],[0.014870009633410218、0.6947797773981148],[0.01478418759402894、0.7684331582472369],[0.03166518933198375,   0.8392744747251855],[0.06115956082472804、0.9024180638379186],[0.10860571254829726、0.9601635183836916],[0.17011504626717094,   1.0057204991427136],[0.25121165844788507、1.0340586363828044],[0.3433729801681099、1.0413332887822182],[0.4340747633053713,   1.0248020469426704],[0.5180659200853382、0.9941894832935652],[0.5905636066620379、0.949568636289012],[0.6483867917457562,   0.8895699510264967],[0.6935845784738898、0.8206748353165457],[0.7288984252469625、0.7487434227072808],[0.7554424386870936,   0.6755670567849011]]

我该如何处理这个问题,铸造?

2 个答案:

答案 0 :(得分:2)

来自dynamic的嵌套集合泛型并不容易。不幸的是,在元素是集合的情况下,转换需要一直在最低层进行。

要获取一个dynamic,您知道它是仅包含List,仅包含List的{​​{1}}(即double,并说服这样的Dart运行时类型系统,您将需要以下内容:

List<List<double>>

List<List<T>> _castNestedList<T>(dynamic l) => (l as List).map((inner) => List<T>.from(inner)).toList(); 正在获取每个内部列表,并将其复制到具有正确的分类类型的新列表。如果列表中会有多次读取,则这比List<T>.from更好,因为在List.cast情况下,每个元素访问都会进行运行时类型检查。

使用Dart 2处理此类铸造是一个已知的痛点。从长远来看,我们希望改善可用性。请参见https://github.com/leafpetersen/cast/issues/1

上的讨论

答案 1 :(得分:0)

首先,您需要获取对列表的引用,然后进行强制转换:

lip: (json['lip'] as List).cast<List<double>>()

或者要了解null:

lip: (json['lip'] as List)?.cast<List<double>>()