in firebase-functions/src/main/java/com/google/firebase/functions/Serializer.java [47:134]
public Object encode(Object obj) {
if (obj == null || obj == JSONObject.NULL) {
return JSONObject.NULL;
}
if (obj instanceof Long) {
// JavaScript can't handle the full range of a long, so we use a wrapped string.
JSONObject wrapped = new JSONObject();
try {
wrapped.put("@type", LONG_TYPE);
wrapped.put("value", obj.toString());
} catch (JSONException e) {
// This should never happen.
throw new RuntimeException("Error encoding Long.", e);
}
return wrapped;
}
if (obj instanceof Number) {
return obj;
}
if (obj instanceof String) {
return obj;
}
if (obj instanceof Boolean) {
return obj;
}
if (obj instanceof JSONObject) {
return obj;
}
if (obj instanceof JSONArray) {
return obj;
}
if (obj instanceof Map) {
JSONObject result = new JSONObject();
Map<?, ?> m = (Map<?, ?>) obj;
for (Object k : m.keySet()) {
if (!(k instanceof String)) {
throw new IllegalArgumentException("Object keys must be strings.");
}
String key = (String) k;
Object value = encode(m.get(k));
try {
result.put(key, value);
} catch (JSONException e) {
// This should never happen.
throw new RuntimeException(e);
}
}
return result;
}
if (obj instanceof List) {
JSONArray result = new JSONArray();
List<?> l = (List<?>) obj;
for (Object o : l) {
result.put(encode(o));
}
return result;
}
if (obj instanceof JSONObject) {
JSONObject result = new JSONObject();
JSONObject m = (JSONObject) obj;
Iterator<String> keys = m.keys();
while (keys.hasNext()) {
String k = keys.next();
if (k == null) {
throw new IllegalArgumentException("Object keys cannot be null.");
}
String key = (String) k;
Object value = encode(m.opt(k));
try {
result.put(key, value);
} catch (JSONException e) {
// This should never happen.
throw new RuntimeException(e);
}
}
return result;
}
if (obj instanceof JSONArray) {
JSONArray result = new JSONArray();
JSONArray l = (JSONArray) obj;
for (int i = 0; i < l.length(); i++) {
Object o = l.opt(i);
result.put(encode(o));
}
return result;
}
throw new IllegalArgumentException("Object cannot be encoded in JSON: " + obj);
}