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;
  }

  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);
}