deserialize method
String?
deserialize(
- DartType targetType,
- String expression,
- TypeHelperContextWithConfig 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,
TypeHelperContextWithConfig context,
bool defaultProvided,
) {
final memberContent = enumValueMapFromType(targetType);
if (memberContent == null) {
return null;
}
final jsonKey = jsonKeyForField(context.fieldElement, context.config);
if (!targetType.isNullableType &&
jsonKey.unknownEnumValue == jsonKeyNullForUndefinedEnumValueFieldName) {
// If the target is not nullable,
throw InvalidGenerationSourceError(
'`$jsonKeyNullForUndefinedEnumValueFieldName` cannot be used with '
'`JsonKey.unknownEnumValue` unless the field is nullable.',
element: context.fieldElement,
);
}
String functionName;
if (targetType.isNullableType || defaultProvided) {
functionName = r'$enumDecodeNullable';
} else {
functionName = r'$enumDecode';
}
context.addMember(memberContent);
final args = [
constMapName(targetType),
expression,
if (jsonKey.unknownEnumValue != null)
'unknownValue: ${jsonKey.unknownEnumValue}',
];
return '$functionName(${args.join(', ')})';
}