fromJsonObject method

Value fromJsonObject(
  1. dynamic json
)

Converts a JSON object to its corresponding Firestore Value representation.

This method recursively converts a JSON object into a Firestore Value object. It handles various JSON data types such as doubles, integers, booleans, maps, arrays, and strings, including those encoded with custom prefixes for locations, references, bytes, and datetimes.

Implementation

Value fromJsonObject(dynamic json) {
  if (json is double) {
    return Value(doubleValue: json);
  }

  if (json is int) {
    return Value(integerValue: json.toString());
  }

  if (json is bool) {
    return Value(booleanValue: json);
  }

  if (json is Map<String, dynamic>) {
    final map = <String, Value>{};
    for (final entry in json.entries) {
      map[entry.key] = fromJsonObject(entry.value);
    }
    return Value(mapValue: MapValue(fields: map));
  }

  if (json is List<dynamic>) {
    final list = <Value>[];
    for (final entry in json) {
      list.add(fromJsonObject(entry));
    }
    return Value(arrayValue: ArrayValue(values: list));
  }

  if (json is String) {
    if (json.startsWith(_locationPrefix)) {
      final strings = json.substring(_locationPrefix.length).split('/');
      final lat = double.parse(strings[0]);
      final lon = double.parse(strings[1]);
      return Value(geoPointValue: LatLng(latitude: lat, longitude: lon));
    }

    if (json.startsWith(_referencePrefix)) {
      final ref = json.substring(_referencePrefix.length);
      return Value(referenceValue: ref);
    }

    if (json.startsWith(_bytesPrefix)) {
      final bytes = json.substring(_bytesPrefix.length);
      return Value(bytesValue: bytes);
    }

    if (json.startsWith(_datetimePrefix)) {
      final datetimeRaw = json.substring(_datetimePrefix.length);
      final datetimeFormatted = DateTime.parse(datetimeRaw).toIso8601String();
      return Value(timestampValue: datetimeFormatted);
    }

    return Value(stringValue: json);
  }

  if (json == null) {
    return Value(nullValue: 'NULL_VALUE');
  }

  throw FormatException('Unknown data type: json=$json');
}