JsonConvert 源码根据T类型解析Map数据为实体类

30 min read
class JsonConvert {
  static final Map<String, JsonConvertFunction> _convertFuncMap = {
    (DailyEntity).toString(): DailyEntity.fromJson,
  };
}

_convertFuncMap 为插件自动生成的映射类, 将(DailyEntity).toString()字符串作为key映射到为DailyEntity.fromJson这个具体类的fromJson方法

asT 方法源码

  T? asT<T extends Object?>(dynamic value) {
    if (value is T) {
      return value;
    }
    final String type = T.toString();  // 1. 将接受的T类型转换为字符type
    try {
      final String valueS = value.toString();
      if (type == "String") {
        return valueS as T;
      } else if (type == "int") {
        final int? intValue = int.tryParse(valueS);
        if (intValue == null) {
          return double.tryParse(valueS)?.toInt() as T?;
        } else {
          return intValue as T;
        }
      } else if (type == "double") {
        return double.parse(valueS) as T;
      } else if (type == "DateTime") {
        return DateTime.parse(valueS) as T;
      } else if (type == "bool") {
        if (valueS == '0' || valueS == '1') {
          return (valueS == '1') as T;
        }
        return (valueS == 'true') as T;
      } else if (type == "Map" || type.startsWith("Map<")) {
        return value as T;
      } else {
        if (_convertFuncMap.containsKey(type)) {   // 2. 根据字符串type映射为T类型的 fromJson函数
          return _convertFuncMap[type]!(value) as T;
        } else {
          throw UnimplementedError('$type unimplemented');
        }
      }
    } catch (e, stackTrace) {
      debugPrint('asT<$T> $e $stackTrace');
      return null;
    }
  }