BytesOrUnicode.fromJson constructor

BytesOrUnicode.fromJson(
  1. Object? json_
)

Returns a new instance from a JSON value. May throw if the value does not have the expected structure.

Implementation

factory BytesOrUnicode.fromJson(Object? json_) {
  Object? json = json_;
  if (json is Map) {
    final rt = json['runtimeType'];
    if (rt is String) {
      json = (
        const ['BytesOrUnicodeString', 'BytesOrUnicodeUint8List'].indexOf(rt),
        json
      );
    } else {
      final MapEntry(:key, :value) = json.entries.first;
      json = (key is int ? key : int.parse(key! as String), value);
    }
  }
  return switch (json) {
    (0, final value) || [0, final value] => BytesOrUnicodeString(
        value is String ? value : (value! as ParsedString).value),
    (1, final value) || [1, final value] => BytesOrUnicodeUint8List(
        (value is Uint8List
            ? value
            : Uint8List.fromList((value! as List).cast()))),
    _ => throw Exception('Invalid JSON $json_'),
  };
}