storageToJsonValue function

Object? storageToJsonValue(
  1. Object? v
)

Encode any Dart value coming out of the engine into a form jsonEncode will accept and that jsonValueToStorage can losslessly reverse.

In particular, BLOBs (List<int> / Uint8List) are wrapped as {"$blob":"<hex>"} so we don't confuse them with regular integer arrays on reload.

Implementation

Object? storageToJsonValue(Object? v) {
  if (v == null) return null;
  if (v is bool || v is num || v is String) return v;
  if (v is Uint8List) return {kBlobJsonTag: _bytesToHex(v)};
  if (v is List<int>) return {kBlobJsonTag: _bytesToHex(v)};
  if (v is List) return v.map(storageToJsonValue).toList();
  if (v is Map) {
    return v.map((k, val) => MapEntry(k.toString(), storageToJsonValue(val)));
  }
  return v.toString();
}