diff --git a/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java b/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java index 60db44d8..fd0d874e 100644 --- a/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java +++ b/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java @@ -443,10 +443,14 @@ final class DefaultTypeAdapters { childGenericType = new TypeInfoCollection(typeOfSrc).getElementType(); } for (Object child : src) { - Type childType = (childGenericType == null || childGenericType == Object.class) - ? child.getClass() : childGenericType; - JsonElement element = context.serialize(child, childType); - array.add(element); + if (child == null) { + array.add(JsonNull.createJsonNull()); + } else { + Type childType = (childGenericType == null || childGenericType == Object.class) + ? child.getClass() : childGenericType; + JsonElement element = context.serialize(child, childType); + array.add(element); + } } return array; } diff --git a/gson/src/test/java/com/google/gson/functional/CollectionTest.java b/gson/src/test/java/com/google/gson/functional/CollectionTest.java index d43d4ce2..9889c050 100644 --- a/gson/src/test/java/com/google/gson/functional/CollectionTest.java +++ b/gson/src/test/java/com/google/gson/functional/CollectionTest.java @@ -153,6 +153,17 @@ public class CollectionTest extends TestCase { Type type = new TypeToken>() {}.getType(); assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type)); } + + public void testCollectionOfObjectWithNullSerialization() { + List target = new ArrayList(); + target.add("Hello"); + target.add(null); + target.add("World"); + assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target)); + + Type type = new TypeToken>() {}.getType(); + assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type)); + } public void testCollectionOfStringsSerialization() { List target = new ArrayList();