fix #680 - make RuntimeTypeAdapterFactory null-safe

This commit is contained in:
Lachlan Coote 2015-08-05 16:27:18 -07:00
parent 77e31ed999
commit 1867457030
2 changed files with 20 additions and 1 deletions

View File

@ -235,6 +235,6 @@ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory {
}
Streams.write(clone, out);
}
};
}.nullSafe();
}
}

View File

@ -167,6 +167,25 @@ public final class RuntimeTypeAdapterFactoryTest extends TestCase {
}
}
public void testSerializeWrappedNullValue() {
TypeAdapterFactory billingAdapter = RuntimeTypeAdapterFactory.of(BillingInstrument.class)
.registerSubtype(CreditCard.class)
.registerSubtype(BankTransfer.class);
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(billingAdapter)
.create();
String serialized = gson.toJson(new BillingInstrumentWrapper(null), BillingInstrumentWrapper.class);
BillingInstrumentWrapper deserialized = gson.fromJson(serialized, BillingInstrumentWrapper.class);
assertNull(deserialized.instrument);
}
static class BillingInstrumentWrapper {
BillingInstrument instrument;
BillingInstrumentWrapper(BillingInstrument instrument) {
this.instrument = instrument;
}
}
static class BillingInstrument {
private final String ownerName;
BillingInstrument(String ownerName) {