toJsonEncodable static method
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 forobject
. Defaults toobject.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();
}
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);
}
try {
return object.toJson();
} catch (e) {
return object;
}
}