Skip to content

Commit 2eb3758

Browse files
authored
Fix RuntimeTypeAdapterFactory (#2139)
* Change the RuntimeTypeAdapterFactoryTest, so it fails because of #712 * Fix RuntimeTypeAdapterFactory Trying to use this class as is results in the type-property not being serialized into the JSON, thus it is not present on deserialization. The fix from #712 (comment) works. No idea why this is not merged yet.
1 parent cbc0af8 commit 2eb3758

2 files changed

Lines changed: 8 additions & 6 deletions

File tree

extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@
1616

1717
package com.google.gson.typeadapters;
1818

19-
import java.io.IOException;
20-
import java.util.LinkedHashMap;
21-
import java.util.Map;
22-
2319
import com.google.gson.Gson;
2420
import com.google.gson.JsonElement;
2521
import com.google.gson.JsonObject;
@@ -30,6 +26,10 @@
3026
import com.google.gson.reflect.TypeToken;
3127
import com.google.gson.stream.JsonReader;
3228
import com.google.gson.stream.JsonWriter;
29+
import java.io.IOException;
30+
import java.util.LinkedHashMap;
31+
import java.util.Map;
32+
3333

3434
/**
3535
* Adapts values whose runtime type may differ from their declaration type. This
@@ -205,7 +205,7 @@ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {
205205

206206
@Override
207207
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
208-
if (type.getRawType() != baseType) {
208+
if (type == null || !baseType.isAssignableFrom(type.getRawType())) {
209209
return null;
210210
}
211211

extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ public void testRuntimeTypeAdapter() {
3434

3535
CreditCard original = new CreditCard("Jesse", 234);
3636
assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}",
37-
gson.toJson(original, BillingInstrument.class));
37+
//do not give the explicit typeOfSrc, because if this would be in a list
38+
//or an attribute, there would also be no hint. See #712
39+
gson.toJson(original));
3840
BillingInstrument deserialized = gson.fromJson(
3941
"{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class);
4042
assertEquals("Jesse", deserialized.ownerName);

0 commit comments

Comments
 (0)