in src/main/java/com/google/firebase/database/utilities/encoding/CustomClassMapper.java [114:174]
private static <T> Object serialize(T obj) {
if (obj == null) {
return null;
} else if (obj instanceof Number) {
if (obj instanceof Float || obj instanceof Double) {
double doubleValue = ((Number) obj).doubleValue();
if (doubleValue <= Long.MAX_VALUE
&& doubleValue >= Long.MIN_VALUE
&& Math.floor(doubleValue) == doubleValue) {
return ((Number) obj).longValue();
}
return doubleValue;
} else if (obj instanceof Long || obj instanceof Integer) {
return obj;
} else {
throw new DatabaseException(
String.format(
"Numbers of type %s are not supported, please use an int, long, float or double",
obj.getClass().getSimpleName()));
}
} else if (obj instanceof String) {
return obj;
} else if (obj instanceof Boolean) {
return obj;
} else if (obj instanceof Character) {
throw new DatabaseException("Characters are not supported, please use Strings");
} else if (obj instanceof Map) {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) obj).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 (obj instanceof Collection) {
if (obj instanceof List) {
List<Object> list = (List<Object>) obj;
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 (obj.getClass().isArray()) {
throw new DatabaseException(
"Serializing Arrays is not supported, please use Lists instead");
} else if (obj instanceof Enum) {
return ((Enum<?>) obj).name();
} else {
Class<T> clazz = (Class<T>) obj.getClass();
BeanMapper<T> mapper = loadOrCreateBeanMapperForClass(clazz);
return mapper.serialize(obj);
}
}