convertJsonValue<T> function

T? convertJsonValue<T>(
  1. Object? raw
)

Converts a raw JSON value to T, or returns null when that would lose or invent data, e.g. "7" to 7.

Implementation

T? convertJsonValue<T>(Object? raw) {
  if (_isType<T, Map<String, dynamic>>()) {
    final map = decodeJsonText(raw);
    // Always a copy, so changing the returned map can't change the model's json.
    return map is Map
        ? _as<T>({for (final e in map.entries) '${e.key}': e.value})
        : null;
  }
  if (raw is T) return raw;
  if (raw == null) return null;
  final Object? value;
  if (_isType<T, int>()) {
    value = _toInt(raw);
  } else if (_isType<T, double>()) {
    value = _toDouble(raw);
  } else if (_isType<T, num>()) {
    value = _toNum(raw);
  } else if (_isType<T, String>()) {
    value = _toText(raw);
  } else if (_isType<T, bool>()) {
    value = _toBool(raw);
  } else if (_isType<T, DateTime>()) {
    value = _toDateTime(raw);
  } else {
    value = null;
  }
  return _as<T>(value);
}