read<T> method

T read<T>(
  1. String key, [
  2. T? defaultValue
])

Reads a value of type T from the backing map by key. The type parameter T must be specified explicitly and cannot be nullable.

Strategy:

  1. If the key is not found and defaultValue is provided, returns defaultValue. Otherwise, throws DogSerializerException.
  2. If the value is already of type T, returns it.
  3. If T is a native type (as per the engine's codec), attempts to coerce the value to T.
  4. Otherwise, uses the engine to deserialize the value into type T.

Implementation

T read<T>(String key, [T? defaultValue]) {
  final value = _backing[key];
  if (value == null) {
    if (defaultValue != null) return defaultValue;
    throw DogSerializerException(message: "Missing required field '$key'", converter: _converter);
  }
  if (value is T) return value;
  if (_engine.codec.isNative(T)) {
    try {
      return _engine.codec.primitiveCoercion.coerce(TypeToken<T>(), value, key);
    } catch (e) {
      throw DogSerializerException(
        message: "Failed to coerce field '$key' to type $T: $e",
        converter: _converter,
        cause: e,
      );
    }
  }
  try {
    return _engine.fromNative<T>(value);
  } catch (e) {
    throw DogSerializerException(
      message: "Failed to deserialize field '$key' to type $T: $e",
      converter: _converter,
      cause: e,
    );
  }
}