Skip to content

Commit

Permalink
Fix RuntimeTypeAdapterFactory (#2139)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
t-oster authored Jul 21, 2022
1 parent cbc0af8 commit 2eb3758
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -205,7 +205,7 @@ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) {

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
if (type.getRawType() != baseType) {
if (type == null || !baseType.isAssignableFrom(type.getRawType())) {
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 2eb3758

Please sign in to comment.