read<T> method
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:
- If the key is not found and
defaultValue
is provided, returnsdefaultValue
. Otherwise, throws DogSerializerException. - If the value is already of type
T
, returns it. - If
T
is a native type (as per the engine's codec), attempts to coerce the value toT
. - 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,
);
}
}