toMap<K, V> static method
Converts an object to a Map with keys of type K
and values of type V
.
- If the object is already a Map with the correct key and value types, it is returned as-is.
- If the object is an empty Map, an empty Map is returned.
- If the object is null, throws a
ParsingException
with anullObject
error. - If the object cannot be converted to a Map with the specified types, throws a
ParsingException
.
object
The object to be converted to a Map with keys of type K
and values of type V
.
mapKey
(Optional) Specifies the key to extract values from a Map object.
listIndex
(Optional) Specifies the index to extract elements from a List object.
Returns a Map<K, V> if conversion is successful.
Throws a ParsingException
if the conversion fails.
Example usage:
final object1 = {'key1': 'value1', 'key2': 'value2'};
final map1 = ConvertObject.toMap<String, String>(object1); // {'key1': 'value1', 'key2': 'value2'}
final object2 = {'key1': 1, 'key2': 2};
final map2 = ConvertObject.toMap<String, int>(object2); // {'key1': 1, 'key2': 2'}
final object3 = 'Hello';
final map3 = ConvertObject.toMap<String, int>(object3); // ParsingException (logs an error)
final object4 = null;
final map4 = ConvertObject.toMap<String, int>(object4); // ParsingException (null object)
Implementation
static Map<K, V> toMap<K, V>(
dynamic object, {
dynamic mapKey,
int? listIndex,
}) {
if (object == null) {
throw ParsingException.nullObject(
parsingInfo: 'toMap',
stackTrace: StackTrace.current,
);
}
if (object is String) return toMap(object.decode());
if (object is Map && object.isEmpty) return <K, V>{};
if (listIndex != null && object is List<dynamic>) {
return toMap(object.of(listIndex));
}
if (mapKey != null && object is Map<dynamic, dynamic>) {
return toMap(object[mapKey]);
}
if (object is Map<K, V>) return object;
try {
return object as Map<K, V>;
} catch (_) {}
try {
return (object as Map)
.map((key, value) => MapEntry(key as K, value as V));
} catch (e, s) {
log(
'toMap() Unsupported Map type <$K, $V>: exception message -> $e',
stackTrace: s,
error: e,
);
throw ParsingException(
error: e.toString(),
parsingInfo: 'toMap',
stackTrace: s,
);
}
}