toJsonEncodable static method

Object? toJsonEncodable(
  1. dynamic object, {
  2. Object? toEncodable(
    1. dynamic object
    )?,
})

A JSON encodable transformer, that resolves the registered ClassReflection of the passed object, and calls ClassReflection.toJson.

  • toEncodable to use when there's no registered ClassReflection for object. Defaults to object.toJson.

Usually used with:

  json.encode(obj, toEncodable: ReflectionFactory.toJsonEncodable);

Implementation

static Object? toJsonEncodable(
  dynamic object, {
  Object? Function(dynamic object)? toEncodable,
}) {
  if (object == null) {
    return null;
  }

  if (object is DateTime) {
    return object.toUtc().toString();
  }

  if (object is Duration) {
    return object.inMilliseconds;
  }

  // `Uri` has no `toJson`, and its runtime type is a private implementation
  // (`_SimpleUri`, `_Uri`) that no reflection can be registered for — so
  // without this it reaches the identity fallback at the end of this method,
  // and whoever called it re-processes the same object forever.
  //
  // `toString()` because `Uri.parse` is its inverse, so the value survives a
  // round trip.
  if (object is Uri) {
    return object.toString();
  }

  var classReflection = _instance.getRegisterClassReflection(
    object.runtimeType,
  );
  if (classReflection != null) {
    return classReflection.toJson(object);
  }

  var enumReflection = _instance.getRegisterEnumReflection(
    object.runtimeType,
  );
  if (enumReflection != null) {
    return enumReflection.toJson(object);
  }

  if (toEncodable != null) {
    return toEncodable(object);
  }

  return JsonEncoder.callToJson(object, fallback: (o) => o);
}