jsonEncodeBytes static method

BuBytes jsonEncodeBytes(
  1. Object? object, {
  2. Object? toEncodable(
    1. Object? object
    )?,
  3. JsonEncodeOptions? options,
  4. String? indent,
})

Encodes directly to raw bytes — no intermediate String involved. This is the direct binary-out counterpart to jsonDecodeBytes/jsonDecode. See jsonEncode for options and indent.

Prefer this over jsonEncode(...).codeUnits or manually re-encoding the resulting String for JsonBinary payloads: going through a Dart String means each byte becomes a UTF-16 code unit, and getting the original wire bytes back out afterwards requires remembering to latin1.encode it (never utf8.encode, which would re-expand bytes ≥ 0x80). Here, JsonBinary bytes are written straight into the output with no re-encoding step at all, and ordinary String values are UTF-8 encoded properly — so there's no encoding pitfall to remember.

Implementation

static BuBytes jsonEncodeBytes(
  Object? object, {
  Object? Function(Object? object)? toEncodable,
  JsonEncodeOptions? options,
  String? indent,
}) {
  final out = BuBytes.empty();
  _encodeValueBytes(
    out,
    object,
    toEncodable,
    options,
    <Object?>[],
    indent,
    0,
  );
  return out;
}