From 2eb37589b53d0d2c292a2187bc87a0967686ac29 Mon Sep 17 00:00:00 2001 From: Thomas Oster Date: Thu, 21 Jul 2022 19:28:48 +0200 Subject: [PATCH] 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 https://github.com/google/gson/issues/712#issuecomment-148955110 works. No idea why this is not merged yet. --- .../gson/typeadapters/RuntimeTypeAdapterFactory.java | 10 +++++----- .../typeadapters/RuntimeTypeAdapterFactoryTest.java | 4 +++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java index 3e8aebcf60..a8c6368c28 100644 --- a/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java +++ b/extras/src/main/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactory.java @@ -16,10 +16,6 @@ package com.google.gson.typeadapters; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; - import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -30,6 +26,10 @@ import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + /** * Adapts values whose runtime type may differ from their declaration type. This @@ -205,7 +205,7 @@ public RuntimeTypeAdapterFactory registerSubtype(Class type) { @Override public TypeAdapter create(Gson gson, TypeToken type) { - if (type.getRawType() != baseType) { + if (type == null || !baseType.isAssignableFrom(type.getRawType())) { return null; } diff --git a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java index 8c62bef7f4..e58ee0f9c3 100644 --- a/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java +++ b/extras/src/test/java/com/google/gson/typeadapters/RuntimeTypeAdapterFactoryTest.java @@ -34,7 +34,9 @@ public void testRuntimeTypeAdapter() { CreditCard original = new CreditCard("Jesse", 234); assertEquals("{\"type\":\"CreditCard\",\"cvv\":234,\"ownerName\":\"Jesse\"}", - gson.toJson(original, BillingInstrument.class)); + //do not give the explicit typeOfSrc, because if this would be in a list + //or an attribute, there would also be no hint. See #712 + gson.toJson(original)); BillingInstrument deserialized = gson.fromJson( "{type:'CreditCard',cvv:234,ownerName:'Jesse'}", BillingInstrument.class); assertEquals("Jesse", deserialized.ownerName);