From b0b6834157e17f0ff916b2c39dcfd38fba65b376 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Mon, 22 Aug 2022 15:55:31 +0200 Subject: [PATCH] Mention that GsonBuilder.registerTypeAdapter makes (de-)serializers null-safe (#1704) --- gson/src/main/java/com/google/gson/GsonBuilder.java | 6 ++++++ gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/gson/src/main/java/com/google/gson/GsonBuilder.java b/gson/src/main/java/com/google/gson/GsonBuilder.java index 3c9f0f52..81fa022d 100644 --- a/gson/src/main/java/com/google/gson/GsonBuilder.java +++ b/gson/src/main/java/com/google/gson/GsonBuilder.java @@ -534,6 +534,12 @@ public final class GsonBuilder { * types! For example, applications registering {@code boolean.class} should also register {@code * Boolean.class}. * + *

{@link JsonSerializer} and {@link JsonDeserializer} are made "{@code null}-safe". This + * means when trying to serialize {@code null}, Gson will write a JSON {@code null} and the + * serializer is not called. Similarly when deserializing a JSON {@code null}, Gson will emit + * {@code null} without calling the deserializer. If it is desired to handle {@code null} values, + * a {@link TypeAdapter} should be used instead. + * * @param type the type definition for the type adapter being registered * @param typeAdapter This object must implement at least one of the {@link TypeAdapter}, * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces. diff --git a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java index 2e00dc9b..d92994fa 100644 --- a/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java +++ b/gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java @@ -53,10 +53,16 @@ public class GsonTypeAdapterTest extends TestCase { fail("Type Adapter should have thrown an exception"); } catch (IllegalStateException expected) { } + // Verify that serializer is made null-safe, i.e. it is not called for null + assertEquals("null", gson.toJson(null, AtomicLong.class)); + try { gson.fromJson("123", AtomicLong.class); fail("Type Adapter should have thrown an exception"); } catch (JsonParseException expected) { } + + // Verify that deserializer is made null-safe, i.e. it is not called for null + assertNull(gson.fromJson(JsonNull.INSTANCE, AtomicLong.class)); } public void testTypeAdapterProperlyConvertsTypes() throws Exception {