encodeReflectively static method

String encodeReflectively(
  1. Object? object, {
  2. bool includeClassName = false,
})

Implementation

static String encodeReflectively(
  Object? object, {
  bool includeClassName = false,
}) {
  if (object == null) {
    return 'null';
  }

  if (object is List) {
    return '[${object.map((item) => encodeReflectively(item)).join(', ')}]';
  }

  if (object is Map) {
    return '{${object.entries.map((e) => '"${e.key}": ${encodeReflectively(e.value)}').join(', ')}}';
  }

  if (object is String) {
    return '"${object.replaceAll('"', '\\"')}"';
  } else if (object is num || object is bool) {
    return object.toString();
  }

  // Attempt to convert custom objects to a map
  final Map<String, dynamic>? jsonMap = _convertObjectToMap(object);

  if (jsonMap == null) {
    throw UnsupportedError(
      'Cannot serialize object of type ${object.runtimeType}',
    );
  }

  final String jsonBody = jsonMap.entries
      .map((entry) => '"${entry.key}": ${encodeReflectively(entry.value)}')
      .join(', ');

  if (includeClassName) {
    final String className = object.runtimeType.toString();
    final String capitalizedClassName =
        '${className[0].toLowerCase()}${className.substring(1)}';
    return '{"$capitalizedClassName": {$jsonBody}}';
  }

  return '{$jsonBody}';
}