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