Support fail on unknown in PolymorphicJsonAdapterFactory. (#792)

Before, this would fail when skipping to find the index of the label.
Note that this still requires the type to have a label field.
This commit is contained in:
Eric Cochran
2019-02-15 11:16:12 -08:00
committed by GitHub
parent f68035859e
commit 126c8ea961
2 changed files with 25 additions and 1 deletions

View File

@@ -233,7 +233,9 @@ public final class PolymorphicJsonAdapterFactory<T> implements JsonAdapter.Facto
}
@Override public Object fromJson(JsonReader reader) throws IOException {
int labelIndex = labelIndex(reader.peekJson());
JsonReader peeked = reader.peekJson();
peeked.setFailOnUnknown(false);
int labelIndex = labelIndex(peeked);
if (labelIndex == -1) {
reader.skipValue();
return defaultValue;

View File

@@ -215,6 +215,18 @@ public final class PolymorphicJsonAdapterFactoryTest {
assertThat(decoded.long_value).isEqualTo(9007199254740993L);
}
@Test public void failOnUnknownMissingTypeLabel() throws IOException {
Moshi moshi = new Moshi.Builder()
.add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
.withSubtype(MessageWithType.class, "success"))
.build();
JsonAdapter<Message> adapter = moshi.adapter(Message.class).failOnUnknown();
MessageWithType decoded = (MessageWithType) adapter.fromJson(
"{\"value\":\"Okay!\",\"type\":\"success\"}");
assertThat(decoded.value).isEqualTo("Okay!");
}
interface Message {
}
@@ -269,4 +281,14 @@ public final class PolymorphicJsonAdapterFactoryTest {
this.long_value = long_value;
}
}
static final class MessageWithType implements Message {
final String type;
final String value;
MessageWithType(String type, String value) {
this.type = type;
this.value = value;
}
}
}