serialize method

  1. @override
String? serialize(
  1. DartType targetType,
  2. String expression,
  3. TypeHelperContextWithConfig context
)
override

Simply returns the expression provided.

By default, JSON encoding in from dart:convert calls toJson() on provided objects.

Implementation

@override
String? serialize(
  DartType targetType,
  String expression,
  TypeHelperContextWithConfig context,
) {
  if (!_canSerialize(context.config, targetType)) {
    return null;
  }

  final interfaceType = targetType as InterfaceType;

  final toJsonArgs = <String>[];

  var toJson = _toJsonMethod(interfaceType);

  if (toJson != null) {
    // Using the `declaration` here so we get the original definition –
    // and not one with the generics already populated.
    toJson = toJson.declaration;

    toJsonArgs.addAll(
      _helperParams(
        context.serialize,
        _encodeHelper,
        interfaceType,
        toJson.parameters.where((element) => element.isRequiredPositional),
        toJson,
      ),
    );
  }

  if (context.config.explicitToJson || toJsonArgs.isNotEmpty) {
    return '$expression${interfaceType.isNullableType ? '?' : ''}'
        '.toJson(${toJsonArgs.map((a) => '$a, ').join()} )';
  }
  return expression;
}