JsonValueDto.encode constructor

JsonValueDto.encode(
  1. Object? value, {
  2. int maxLength = 4096,
})

Best-effort conversion of an arbitrary Dart value to a JsonValueDto.

Scalars, lists, and string-keyed maps are shipped directly. Anything else becomes an OpaqueValueDto using toString().

Implementation

factory JsonValueDto.encode(Object? value, {int maxLength = 4096}) {
  if (value == null || value is bool || value is num || value is String) {
    if (value is String && value.length > maxLength) {
      return OpaqueValueDto(
        typeName: 'String',
        repr: value.substring(0, maxLength),
        truncated: true,
      );
    }
    return DirectValueDto(value);
  }
  if (value is List) {
    try {
      final encoded = value
          .map((e) => JsonValueDto.encode(e, maxLength: maxLength).toJson())
          .toList();
      return DirectValueDto(encoded);
    } catch (_) {
      return _opaqueOf(value, maxLength);
    }
  }
  if (value is Map) {
    try {
      final encoded = <String, Object?>{};
      for (final entry in value.entries) {
        encoded[entry.key.toString()] =
            JsonValueDto.encode(entry.value, maxLength: maxLength).toJson();
      }
      return DirectValueDto(encoded);
    } catch (_) {
      return _opaqueOf(value, maxLength);
    }
  }
  return _opaqueOf(value, maxLength);
}