decode method

String decode(
  1. String expr,
  2. DartType type,
  3. int depth
)

the code that turns the JSON value expr into a type

Implementation

String decode(String expr, DartType type, int depth) {
  bool nullable = type.nullabilitySuffix == NullabilitySuffix.question;
  if (type is! InterfaceType || type.isDartCoreObject) {
    return type is InterfaceType && !nullable ? '$expr as Object' : expr;
  }
  String q = nullable ? '?' : '';
  if (type.isDartCoreInt) return '($expr as num$q)$q.toInt()';
  if (type.isDartCoreDouble) return '($expr as num$q)$q.toDouble()';
  if (type.isDartCoreNum) return '$expr as num$q';
  if (type.isDartCoreString) return '$expr as String$q';
  if (type.isDartCoreBool) return '$expr as bool$q';
  String value;
  String v = 'e$depth';
  if (JobRegistryBuilder.isDateTime(type)) {
    value = 'DateTime.parse($expr as String)';
  } else if (type.element is EnumElement) {
    value =
        '${typeCode(type, nullable: false)}.values.byName($expr as String)';
  } else if (type.isDartCoreList) {
    DartType item = type.typeArguments.first;
    value =
        '<${typeCode(item)}>[for (Object? $v in $expr as List<Object?>) '
        '${decode(v, item, depth + 1)}]';
  } else {
    DartType item = type.typeArguments.last;
    value =
        '<String, ${typeCode(item)}>{for (MapEntry<String, Object?> $v in '
        '($expr as Map<String, Object?>).entries) '
        '$v.key: ${decode('$v.value', item, depth + 1)}}';
  }
  return nullable ? '($expr == null ? null : $value)' : value;
}