From ed2b25ddefa15b571d2c5d4c82506632f694fed5 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Sat, 1 Oct 2011 00:22:33 +0000 Subject: [PATCH] Don't serialize nulls in JsonElementWriter if setSerializeNulls(false) --- .../gson/internal/bind/JsonElementWriter.java | 6 ++++-- .../internal/bind/JsonElementWriterTest.java | 21 ++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonElementWriter.java b/gson/src/main/java/com/google/gson/internal/bind/JsonElementWriter.java index 3328cdc2..3c31000d 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/JsonElementWriter.java +++ b/gson/src/main/java/com/google/gson/internal/bind/JsonElementWriter.java @@ -71,8 +71,10 @@ public final class JsonElementWriter extends JsonWriter { private void put(JsonElement value) { if (pendingName != null) { - JsonObject object = (JsonObject) peek(); - object.add(pendingName, value); + if (!value.isJsonNull() || getSerializeNulls()) { + JsonObject object = (JsonObject) peek(); + object.add(pendingName, value); + } pendingName = null; } else if (stack.isEmpty()) { product = value; diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementWriterTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementWriterTest.java index dfe4fb25..5246b6f3 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementWriterTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementWriterTest.java @@ -23,7 +23,6 @@ public final class JsonElementWriterTest extends TestCase { // TODO: more tests // TODO: figure out what should be returned by an empty writer - // TODO: test when serialize nulls is false public void testArray() throws IOException { JsonElementWriter writer = new JsonElementWriter(); @@ -97,4 +96,24 @@ public final class JsonElementWriterTest extends TestCase { } catch (IOException expected) { } } + + public void testSerializeNullsFalse() throws IOException { + JsonElementWriter writer = new JsonElementWriter(); + writer.setSerializeNulls(false); + writer.beginObject(); + writer.name("A"); + writer.nullValue(); + writer.endObject(); + assertEquals("{}", writer.get().toString()); + } + + public void testSerializeNullsTrue() throws IOException { + JsonElementWriter writer = new JsonElementWriter(); + writer.setSerializeNulls(true); + writer.beginObject(); + writer.name("A"); + writer.nullValue(); + writer.endObject(); + assertEquals("{\"A\":null}", writer.get().toString()); + } }