serialize method
Object?
serialize(
- DartType targetType,
- String expression,
- TypeHelperContextWithConfig context
override
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
Object? serialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
) {
final converter = _typeConverter(targetType, context);
if (converter == null) {
return null;
}
if (!converter.fieldType.isNullableType && targetType.isNullableType) {
const converterToJsonName = r'_$JsonConverterToJson';
context.addMember('''
Json? $converterToJsonName<Json, Value>(
Value? value,
Json? Function(Value value) toJson,
) => ${ifNullOrElse('value', 'null', 'toJson(value)')};
''');
return _nullableJsonConverterLambdaResult(
converter,
name: converterToJsonName,
targetType: targetType,
expression: expression,
callback: '${converter.accessString}.toJson',
);
}
return LambdaResult(expression, '${converter.accessString}.toJson');
}