Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #1697: Mention that GsonBuilder.registerTypeAdapter makes (de-)serializers null-safe #1704

Merged
merged 2 commits into from
Aug 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions gson/src/main/java/com/google/gson/GsonBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,12 @@ public GsonBuilder setDateFormat(int dateStyle, int timeStyle) {
* types! For example, applications registering {@code boolean.class} should also register {@code
* Boolean.class}.
*
* <p>{@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.
Expand Down
6 changes: 6 additions & 0 deletions gson/src/test/java/com/google/gson/GsonTypeAdapterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,16 @@ public void testTypeAdapterThrowsException() throws Exception {
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 {
Expand Down