valueTo<T extends Object?, VV extends Object?> method
T
valueTo<T extends Object?, VV extends Object?>({
- required K key,
- required T parse(
- VV v
- bool? allowHex,
- StringEncoding? encoding,
- bool asBytes = false,
- T onMissing()?,
- T onError(
- JsonParserError err
- bool acceptSnakeCase = false,
- bool acceptCamelCase = false,
Implementation
T valueTo<T extends Object?, VV extends Object?>({
required K key,
required T Function(VV v) parse,
bool? allowHex,
StringEncoding? encoding,
bool asBytes = false,
T Function()? onMissing,
T Function(JsonParserError err)? onError,
/// Also accepts the snake_case version of [key] when looking up JSON fields.
/// Only applicable when [K] is `String`.
bool acceptSnakeCase = false,
bool acceptCamelCase = false,
}) {
try {
V? value = this[key];
if (value == null && key is String) {
if (acceptSnakeCase) {
value = this[StringUtils.camelToSnake(key)];
} else if (acceptCamelCase) {
value = this[StringUtils.snakeToCamel(key, capitalizeFirst: false)];
}
}
if (value == null) {
if (JsonParser._isNull<VV>()) return parse(null as VV);
if (JsonParser._isNull<T>()) return null as T;
if (onMissing != null) return onMissing();
if (!containsKey(key)) throw JsonParserError("Missing key: '$key'.");
throw JsonParserError("Null value for key: '$key'.");
}
return JsonParser.valueTo(
value: value,
parse: parse,
allowHex: allowHex,
asBytes: asBytes,
encoding: encoding,
);
} on JsonParserError catch (e) {
if (onError != null) return onError(e);
rethrow;
}
}