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.
This commit is contained in:
Thomas Oster 2022-07-21 19:28:48 +02:00 committed by GitHub
parent cbc0af867b
commit 2eb37589b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 6 deletions

View File

@ -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.TypeAdapterFactory;
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 final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (type.getRawType() != baseType) {
if (type == null || !baseType.isAssignableFrom(type.getRawType())) {
return null;
}

View File

@ -34,7 +34,9 @@ public final class RuntimeTypeAdapterFactoryTest extends TestCase {
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);