Fixed custom serilization invocation to correctly handle nulls returned by custom serializer.
This commit is contained in:
parent
6387c9028e
commit
60ef777efc
|
@ -184,7 +184,9 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
|
|||
objTypePair = pair.getSecond();
|
||||
start(objTypePair);
|
||||
try {
|
||||
return serializer.serialize(objTypePair.getObject(), objTypePair.getType(), context);
|
||||
JsonElement element =
|
||||
serializer.serialize(objTypePair.getObject(), objTypePair.getType(), context);
|
||||
return element == null ? JsonNull.createJsonNull() : element;
|
||||
} finally {
|
||||
end(objTypePair);
|
||||
}
|
||||
|
|
|
@ -16,11 +16,17 @@
|
|||
|
||||
package com.google.gson.functional;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonSerializationContext;
|
||||
import com.google.gson.JsonSerializer;
|
||||
import com.google.gson.common.TestTypes.Base;
|
||||
import com.google.gson.common.TestTypes.BaseSerializer;
|
||||
import com.google.gson.common.TestTypes.ClassWithBaseArrayField;
|
||||
|
@ -28,8 +34,6 @@ import com.google.gson.common.TestTypes.ClassWithBaseField;
|
|||
import com.google.gson.common.TestTypes.Sub;
|
||||
import com.google.gson.common.TestTypes.SubSerializer;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Functional Test exercising custom serialization only. When test applies to both
|
||||
* serialization and deserialization then add it to CustomTypeAdapterTest.
|
||||
|
@ -83,4 +87,17 @@ public class CustomSerializerTest extends TestCase {
|
|||
JsonObject base = json.get("base").getAsJsonObject();
|
||||
assertEquals(BaseSerializer.NAME, base.get(Base.SERIALIZER_KEY).getAsString());
|
||||
}
|
||||
|
||||
public void testSerializerReturnsNull() {
|
||||
Gson gson = new GsonBuilder()
|
||||
.registerTypeAdapter(Base.class, new JsonSerializer<Base>() {
|
||||
public JsonElement serialize(Base src, Type typeOfSrc, JsonSerializationContext context) {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.create();
|
||||
JsonElement json = gson.toJsonTree(new Base());
|
||||
System.out.println(json);
|
||||
assertTrue(json.isJsonNull());
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user