encodeReflectively static method

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

Recursively encodes an object into a JSON-compatible string.

Supports basic types, lists, maps, and objects with a toJson method. Optionally includes the class name as a wrapper for custom objects.

  • object: The object to be encoded.
  • includeClassName: If true, wraps custom objects with their class name.

Returns: A JSON-compatible string representation of the object.

Implementation

static String encodeReflectively(Object? object,
    {bool includeClassName = false}) {
  if (object == null) return 'null';
  if (object is num || object is bool) return object.toString();
  if (object is String) return jsonEncode(object);
  if (object is List) return '[${object.map(encodeReflectively).join(', ')}]';
  if (object is Map) {
    return '{${object.entries.map((e) => '"${e.key}": ${encodeReflectively(e.value)}').join(', ')}}';
  }

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

  final jsonBody = jsonMap.entries
      .map((e) => '"${e.key}": ${encodeReflectively(e.value)}')
      .join(', ');
  return includeClassName
      ? '{"${_formatClassName(object.runtimeType)}": {$jsonBody}}'
      : '{$jsonBody}';
}