in encoders/firebase-encoders-json/src/main/java/com/google/firebase/encoders/json/JsonValueObjectEncoderContext.java [227:325]
JsonValueObjectEncoderContext add(@Nullable Object o, boolean inline) throws IOException {
if (inline && cannotBeInline(o)) {
throw new EncodingException(
String.format("%s cannot be encoded inline", o == null ? null : o.getClass()));
}
if (o == null) {
jsonWriter.nullValue();
return this;
}
if (o instanceof Number) {
jsonWriter.value((Number) o);
return this;
}
if (o.getClass().isArray()) {
// Byte[] are a special case of arrays, because they are not mapped to an array, but to a
// string.
if (o instanceof byte[]) {
return add((byte[]) o);
}
jsonWriter.beginArray();
if (o instanceof int[]) {
for (int item : (int[]) o) {
jsonWriter.value(item);
}
} else if (o instanceof long[]) {
for (long item : (long[]) o) {
add(item);
}
} else if (o instanceof double[]) {
for (double item : (double[]) o) {
jsonWriter.value(item);
}
} else if (o instanceof boolean[]) {
for (boolean item : (boolean[]) o) {
jsonWriter.value(item);
}
} else if (o instanceof Number[]) {
for (Number item : (Number[]) o) {
add(item, false);
}
} else {
for (Object item : (Object[]) o) {
add(item, false);
}
}
jsonWriter.endArray();
return this;
}
if (o instanceof Collection) {
Collection collection = (Collection) o;
jsonWriter.beginArray();
for (Object elem : collection) {
add(elem, false);
}
jsonWriter.endArray();
return this;
}
if (o instanceof Map) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) o;
jsonWriter.beginObject();
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object key = entry.getKey();
try {
add((String) key, entry.getValue());
} catch (ClassCastException ex) {
throw new EncodingException(
String.format(
"Only String keys are currently supported in maps, got %s of type %s instead.",
key, key.getClass()),
ex);
}
}
jsonWriter.endObject();
return this;
}
@SuppressWarnings("unchecked") // safe because get the encoder by checking the object's type.
ObjectEncoder<Object> objectEncoder = (ObjectEncoder<Object>) objectEncoders.get(o.getClass());
if (objectEncoder != null) {
return doEncode(objectEncoder, o, inline);
}
@SuppressWarnings("unchecked") // safe because get the encoder by checking the object's type.
ValueEncoder<Object> valueEncoder = (ValueEncoder<Object>) valueEncoders.get(o.getClass());
if (valueEncoder != null) {
valueEncoder.encode(o, this);
return this;
}
// Process enum last if it does not have a custom encoder registered.
if (o instanceof Enum) {
add(((Enum) o).name());
return this;
}
return doEncode(fallbackEncoder, o, inline);
}