deserialize method
Returns Dart code that deserializes an expression
representing a JSON
literal to into targetType
.
If targetType
is not supported, returns null
.
Let's say you want to deserialize a class Foo
by taking an int
stored
in a JSON literal and calling the Foo.fromInt
constructor.
Treating expression
as a opaque Dart expression representing a JSON
literal, the deserialize implementation could be a simple as:
String deserialize(DartType targetType, String expression) =>
"new Foo.fromInt($expression)";
```.
Note that [targetType] is not used here. If you wanted to support many
types of [targetType] you could write:
```dart
String deserialize(DartType targetType, String expression) =>
"new ${targetType.name}.fromInt($expression)";
```.
Implementation
@override
String? deserialize(
DartType targetType,
String expression,
TypeHelperContextWithConfig context,
bool defaultProvided,
) {
if (!typeChecker.isExactlyType(targetType)) {
return null;
}
final resolvedGenericType = genericType(targetType);
var itemSubVal =
context.deserialize(resolvedGenericType, closureArg)!.toString();
final targetTypeIsNullable = defaultProvided || targetType.isNullableType;
var output = '$expression as List';
// If `itemSubVal` is the same and it's not a Set, then we don't need to do
// anything fancy
if (closureArg == itemSubVal && typeChecker.isExactlyType(targetType)) {
return wrapNullableIfNecessary(
expression,
deserializeFromIterableExpression(output, resolvedGenericType),
targetTypeIsNullable);
}
output = '($output)';
if (closureArg != itemSubVal) {
final lambda = LambdaResult.process(itemSubVal);
output += '.map($lambda)';
}
output = deserializeFromIterableExpression(output, resolvedGenericType);
return wrapNullableIfNecessary(expression, output, targetTypeIsNullable);
}