Honor our 'ignore nulls' policy when converting objects to JSON trees.

This commit is contained in:
Jesse Wilson 2011-10-23 20:28:04 +00:00
parent 290fb69a50
commit 052c9ce0ce
2 changed files with 14 additions and 9 deletions

View File

@ -27,6 +27,7 @@ import com.google.gson.internal.bind.CollectionTypeAdapterFactory;
import com.google.gson.internal.bind.DateTypeAdapter;
import com.google.gson.internal.bind.ExcludedTypeAdapterFactory;
import com.google.gson.internal.bind.JsonElementReader;
import com.google.gson.internal.bind.JsonElementWriter;
import com.google.gson.internal.bind.MapTypeAdapterFactory;
import com.google.gson.internal.bind.MiniGson;
import com.google.gson.internal.bind.ObjectTypeAdapter;
@ -400,9 +401,9 @@ public final class Gson {
*/
@SuppressWarnings({"unchecked", "rawtypes"}) // the caller is required to make src and typeOfSrc consistent
public JsonElement toJsonTree(Object src, Type typeOfSrc) {
// Serialize 'src' to JSON, then deserialize that to a JSON tree.
TypeAdapter adapter = miniGson.getAdapter(TypeToken.get(typeOfSrc));
return adapter.toJsonElement(src);
JsonElementWriter writer = new JsonElementWriter();
toJson(src, typeOfSrc, writer);
return writer.get();
}
/**

View File

@ -1,16 +1,14 @@
package com.google.gson.functional;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import junit.framework.TestCase;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.common.TestTypes.BagOfPrimitives;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import junit.framework.TestCase;
/**
* Functional tests for {@link Gson#toJsonTree(Object)} and
@ -62,6 +60,12 @@ public class JsonTreeTest extends TestCase {
assertEquals(json1, json2);
}
public void testJsonTreeNull() {
BagOfPrimitives bag = new BagOfPrimitives(10L, 5, false, null);
JsonObject jsonElement = (JsonObject) gson.toJsonTree(bag, BagOfPrimitives.class);
assertFalse(jsonElement.has("stringValue"));
}
private void assertContains(JsonObject json, JsonPrimitive child) {
for (Map.Entry<String, JsonElement> entry : json.entrySet()) {
JsonElement node = entry.getValue();