deserialize method
String?
deserialize(
- DartType targetType,
- String expression,
- TypeHelperContext context,
- bool defaultProvided,
override
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,
TypeHelperContext context,
bool defaultProvided,
) {
if (!(coreIterableTypeChecker.isExactlyType(targetType) ||
_coreListChecker.isExactlyType(targetType) ||
_coreSetChecker.isExactlyType(targetType))) {
return null;
}
final iterableGenericType = coreIterableGenericType(targetType);
final itemSubVal = context.deserialize(iterableGenericType, closureArg)!;
var output = '$expression as List<dynamic>';
final targetTypeIsNullable = defaultProvided || targetType.isNullableType;
if (targetTypeIsNullable) {
output += '?';
}
// If `itemSubVal` is the same and it's not a Set, then we don't need to do
// anything fancy
if (closureArg == itemSubVal &&
!_coreSetChecker.isExactlyType(targetType)) {
return output;
}
output = '($output)';
var optionalQuestion = targetTypeIsNullable ? '?' : '';
if (closureArg != itemSubVal) {
final lambda = LambdaResult.process(itemSubVal);
output += '$optionalQuestion.map($lambda)';
// No need to include the optional question below – it was used here!
optionalQuestion = '';
}
if (_coreListChecker.isExactlyType(targetType)) {
output += '$optionalQuestion.toList()';
} else if (_coreSetChecker.isExactlyType(targetType)) {
output += '$optionalQuestion.toSet()';
}
return output;
}