mirror of
https://github.com/fankes/moshi.git
synced 2025-10-19 16:09:21 +08:00
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:
@@ -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) {
|
||||
|
@@ -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")
|
||||
|
Reference in New Issue
Block a user