toEncodableJSON function

Object? toEncodableJSON(
  1. Object? o
)

Ensures that o is an encodable JSON tree.

Implementation

Object? toEncodableJSON(Object? o) {
  if (o == null) return null;
  if (o is num) return o;
  if (o is bool) return o;
  if (o is String) return o;

  if (o is List) return toEncodableJSONList(o);
  if (o is Map) return toEncodableJSONMap(o);
  if (o is Set) return toEncodableJSONList(o.toList());

  Object encodable;
  try {
    dynamic d = o;
    if (d.toJson != null) {
      encodable = d.toJson();
    } else {
      encodable = o.toString();
    }
  } catch (e) {
    encodable = o.toString();
  }

  return toEncodableJSON(encodable);
}