diff --git a/adapters/src/main/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.java b/adapters/src/main/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.java index 02023b7..73e64b6 100644 --- a/adapters/src/main/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.java +++ b/adapters/src/main/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactory.java @@ -233,7 +233,9 @@ public final class PolymorphicJsonAdapterFactory 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; diff --git a/adapters/src/test/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactoryTest.java b/adapters/src/test/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactoryTest.java index 816ba66..cf66e5c 100644 --- a/adapters/src/test/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactoryTest.java +++ b/adapters/src/test/java/com/squareup/moshi/adapters/PolymorphicJsonAdapterFactoryTest.java @@ -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 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; + } + } }