mapRecordContainingContainerToJson function
Maps container types (like List, Map, Set) containing Records to their JSON representation.
It should not be called for SerializableModel types. These handle the "Record in container" mapping internally already.
It is only supposed to be called from generated protocol code.
Returns either a List<dynamic> (for List, Sets, and Maps with non-String keys) or a Map<String, dynamic> in case the input was a Map<String, …>.
Implementation
Object? mapRecordContainingContainerToJson(Object obj) {
if (obj is! Iterable && obj is! Map) {
throw ArgumentError.value(
obj,
'obj',
'The object to serialize should be of type List, Map, or Set',
);
}
dynamic mapIfNeeded(Object? obj) {
return switch (obj) {
Record record => mapRecordToJson(record),
Iterable iterable => mapRecordContainingContainerToJson(iterable),
Map map => mapRecordContainingContainerToJson(map),
Object? value => value,
};
}
switch (obj) {
case Map<String, dynamic>():
return {
for (var entry in obj.entries) entry.key: mapIfNeeded(entry.value),
};
case Map():
return [
for (var entry in obj.entries)
{
'k': mapIfNeeded(entry.key),
'v': mapIfNeeded(entry.value),
}
];
case Iterable():
return [
for (var e in obj) mapIfNeeded(e),
];
}
return obj;
}