dynamicFieldToJson method

Object? dynamicFieldToJson(
  1. Object? object, {
  2. bool forProtocol = false,
})

Returns a JSON-encodable structure for a dynamic model field.

Recursively encodes List, Set, and Map children so each element keeps type information via className / data wrappers.

When forProtocol is true, nested ProtocolSerialization values use ProtocolSerialization.toJsonForProtocol.

Module and shared package protocols override this method to resolve host project types via registered host protocols.

Implementation

Object? dynamicFieldToJson(
  Object? object, {
  bool forProtocol = false,
}) {
  return switch (object) {
    List() => {
      'className': 'List',
      'data': [
        for (final e in object)
          dynamicFieldToJson(e, forProtocol: forProtocol),
      ],
    },
    Set() => {
      'className': 'Set',
      'data': [
        for (final e in object)
          dynamicFieldToJson(e, forProtocol: forProtocol),
      ],
    },
    Map()
        when object is Map<String, dynamic> ||
            object.keys.every((k) => k is String) =>
      {
        'className': 'Map',
        'data': {
          for (final e in object.entries)
            e.key as String: dynamicFieldToJson(
              e.value,
              forProtocol: forProtocol,
            ),
        },
      },
    Map() => {
      'className': 'Map',
      'data': [
        for (final e in object.entries)
          {
            'k': dynamicFieldToJson(e.key, forProtocol: forProtocol),
            'v': dynamicFieldToJson(e.value, forProtocol: forProtocol),
          },
      ],
    },
    _ => _toEncodable(wrapWithClassName(object), forProtocol),
  };
}