in firebase-database/src/main/java/com/google/firebase/database/core/utilities/encoding/CustomClassMapper.java [110:170]
private static <T> Object serialize(T o) {
if (o == null) {
return null;
} else if (o instanceof Number) {
if (o instanceof Float || o instanceof Double) {
double doubleValue = ((Number) o).doubleValue();
if (doubleValue <= Long.MAX_VALUE
&& doubleValue >= Long.MIN_VALUE
&& Math.floor(doubleValue) == doubleValue) {
return ((Number) o).longValue();
}
return doubleValue;
} else if (o instanceof Long || o instanceof Integer) {
return o;
} else {
throw new DatabaseException(
String.format(
"Numbers of type %s are not supported, please use an int, long, float or double",
o.getClass().getSimpleName()));
}
} else if (o instanceof String) {
return o;
} else if (o instanceof Boolean) {
return o;
} else if (o instanceof Character) {
throw new DatabaseException("Characters are not supported, please use Strings");
} else if (o instanceof Map) {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) o).entrySet()) {
Object key = entry.getKey();
if (key instanceof String) {
String keyString = (String) key;
result.put(keyString, serialize(entry.getValue()));
} else {
throw new DatabaseException("Maps with non-string keys are not supported");
}
}
return result;
} else if (o instanceof Collection) {
if (o instanceof List) {
List<Object> list = (List<Object>) o;
List<Object> result = new ArrayList<>(list.size());
for (Object object : list) {
result.add(serialize(object));
}
return result;
} else {
throw new DatabaseException(
"Serializing Collections is not supported, " + "please use Lists instead");
}
} else if (o.getClass().isArray()) {
throw new DatabaseException(
"Serializing Arrays is not supported, please use Lists " + "instead");
} else if (o instanceof Enum) {
return ((Enum<?>) o).name();
} else {
Class<T> clazz = (Class<T>) o.getClass();
BeanMapper<T> mapper = loadOrCreateBeanMapperForClass(clazz);
return mapper.serialize(o);
}
}