Allow serialization of nulls in a "List<Object>" type.

This commit is contained in:
Joel Leitch 2009-09-29 20:34:35 +00:00
parent e5ed1cc59a
commit 933a3e5150
2 changed files with 19 additions and 4 deletions

View File

@ -443,10 +443,14 @@ final class DefaultTypeAdapters {
childGenericType = new TypeInfoCollection(typeOfSrc).getElementType(); childGenericType = new TypeInfoCollection(typeOfSrc).getElementType();
} }
for (Object child : src) { for (Object child : src) {
Type childType = (childGenericType == null || childGenericType == Object.class) if (child == null) {
? child.getClass() : childGenericType; array.add(JsonNull.createJsonNull());
JsonElement element = context.serialize(child, childType); } else {
array.add(element); Type childType = (childGenericType == null || childGenericType == Object.class)
? child.getClass() : childGenericType;
JsonElement element = context.serialize(child, childType);
array.add(element);
}
} }
return array; return array;
} }

View File

@ -153,6 +153,17 @@ public class CollectionTest extends TestCase {
Type type = new TypeToken<List<Object>>() {}.getType(); Type type = new TypeToken<List<Object>>() {}.getType();
assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type)); assertEquals("[\"Hello\",\"World\"]", gson.toJson(target, type));
} }
public void testCollectionOfObjectWithNullSerialization() {
List<Object> target = new ArrayList<Object>();
target.add("Hello");
target.add(null);
target.add("World");
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target));
Type type = new TypeToken<List<Object>>() {}.getType();
assertEquals("[\"Hello\",null,\"World\"]", gson.toJson(target, type));
}
public void testCollectionOfStringsSerialization() { public void testCollectionOfStringsSerialization() {
List<String> target = new ArrayList<String>(); List<String> target = new ArrayList<String>();