validateAndSerialize static method

String validateAndSerialize(
  1. dynamic value, [
  2. String? key
])

Validates and attempts to serialize a value to JSON.

This is a convenience method that validates and then attempts JSON serialization to ensure the value is truly serializable.

Parameters:

  • value: The value to validate and serialize
  • key: Optional key name for error messages

Throws:

Returns: The JSON-encoded string representation of the value.

Implementation

static String validateAndSerialize(dynamic value, [String? key]) {
  final path = key ?? 'root';
  validate(value, path);

  try {
    return jsonEncode(value);
  } catch (e) {
    throw StateError(
      'Failed to serialize value at path "$path": $e. '
      'Type: ${value.runtimeType}.',
    );
  }
}