serialize method
String?
serialize(
- DartType targetType,
- String expression,
- TypeHelperContextWithConfig context
inherited
Returns Dart code that serializes an expression
representing a Dart
object of type targetType
.
If targetType
is not supported, returns null
.
Let's say you want to serialize a class Foo
as just its id
property
of type int
.
Treating expression
as a opaque Dart expression, the serialize
implementation could be a simple as:
String serialize(DartType targetType, String expression) =>
"$expression.id";
```.
Implementation
@override
String? serialize(DartType targetType, String expression,
TypeHelperContextWithConfig context) {
if ((!typeChecker.isAssignableFromType(targetType)) ||
_isDartCoreIterable<T>()) {
return null;
}
// This block will yield a regular list, which works fine for JSON
// Although it's possible that child elements may be marked unsafe
final itemType = genericType(targetType);
final subField = context.serialize(itemType, closureArg)!;
final targetTypeIsNullable = targetType.isNullableType;
final optionalQuestion = targetTypeIsNullable ? '?' : '';
// In the case of trivial JSON types (int, String, etc), `subField`
// will be identical to `substitute` – so no explicit mapping is needed.
// If they are not equal, then we to write out the substitution.
if (subField != closureArg) {
final lambda = LambdaResult.process(subField);
expression = '$expression$optionalQuestion.map($lambda)';
// expression now represents an Iterable (even if it started as a List
// ...resetting `isList` to `false`.
//isList = false;
}
/*if (!isList) {
// If the static type is not a List, generate one.
return expression += '$optionalQuestion.iter$optionalQuestion.toList()';
}
return expression + optionalQuestion + '.asList()';*/
return serializeToList(expression, itemType, targetTypeIsNullable);
}