Skip to content

Commit

Permalink
Mention that GsonBuilder.registerTypeAdapter makes (de-)serialiers nu…
Browse files Browse the repository at this point in the history
…ll-safe
  • Loading branch information
Marcono1234 committed May 21, 2020
1 parent ceae88b commit e643d17
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
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 @@ -487,6 +487,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

0 comments on commit e643d17

Please sign in to comment.