mirror of
https://github.com/fankes/moshi.git
synced 2025-10-19 16:09:21 +08:00
Revert "Don't allow toJson() serialization on polymorphic defau… (#1025)
This reverts commit 6323a0b7c8
.
This makes it difficult for a client to take a server-provided value,
modify it, and send it back.
This commit is contained in:
@@ -275,9 +275,6 @@ public final class PolymorphicJsonAdapterFactory<T> implements JsonAdapter.Facto
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override public void toJson(JsonWriter writer, Object value) throws IOException {
|
@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();
|
Class<?> type = value.getClass();
|
||||||
int labelIndex = subtypes.indexOf(type);
|
int labelIndex = subtypes.indexOf(type);
|
||||||
if (labelIndex == -1) {
|
if (labelIndex == -1) {
|
||||||
|
@@ -105,24 +105,6 @@ public final class PolymorphicJsonAdapterFactoryTest {
|
|||||||
assertThat(message).isNull();
|
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() {
|
@Test public void unregisteredSubtype() {
|
||||||
Moshi moshi = new Moshi.Builder()
|
Moshi moshi = new Moshi.Builder()
|
||||||
.add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
|
.add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
|
||||||
|
Reference in New Issue
Block a user