Don't allow toJson() serialization on polymorphic default values

This type explicitly indicates an unknown value. This is an explosive case, but an alternative could be to just write null into the writer?
This commit is contained in:
Zac Sweers
2019-10-31 15:13:22 -04:00
parent 541b53964c
commit 6323a0b7c8
2 changed files with 21 additions and 0 deletions

View File

@@ -275,6 +275,9 @@ public final class PolymorphicJsonAdapterFactory<T> implements JsonAdapter.Facto
}
@Override public void toJson(JsonWriter writer, Object value) throws IOException {
if (defaultValueSet && value == defaultValue) {
throw new IllegalArgumentException("Cannot serialize default value instance: " + value);
}
Class<?> type = value.getClass();
int labelIndex = subtypes.indexOf(type);
if (labelIndex == -1) {

View File

@@ -105,6 +105,24 @@ public final class PolymorphicJsonAdapterFactoryTest {
assertThat(message).isNull();
}
@Test public void toJsonDefaultValue() {
Error fallbackError = new Error(Collections.<String, Object>emptyMap());
Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
.withSubtype(Success.class, "success")
.withSubtype(Error.class, "error")
.withDefaultValue(fallbackError))
.build();
JsonAdapter<Message> adapter = moshi.adapter(Message.class);
try {
String json = adapter.toJson(fallbackError);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessageContaining("Cannot serialize default value instance");
}
}
@Test public void unregisteredSubtype() {
Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(Message.class, "type")