Adopt JsonElementWriter in GSON.

Add setSerializeNulls() to JsonWriter, so nulls can be skipped from serialization. This does not yet impact JsonElementWriter.

One change in behavior: if the only value is skipped, we now emit "null" rather than "".
This commit is contained in:
Jesse Wilson 2011-09-30 07:08:44 +00:00
parent 364de80611
commit bb7f0b6bb0
7 changed files with 140 additions and 51 deletions

View File

@ -54,8 +54,16 @@ GSON 1.x sometimes sets subclass fields when an InstanceCreator returns a subcla
GSON 2.x sets fields of the requested type only
com.google.gson.functional.InstanceCreatorTest.testInstanceCreatorReturnsSubTypeForField
GSON 1.x applies different rules for versioning for classes vs fields. So, if you deserialize a
JSON into a field that is supposed to be skipped, the field is set to null (or default value).
However, if you deserialize it to a top-level class, a default instance is returned.
GSON 2.x returns null for the top-level class.
com.google.gson.functional.VersioningTest.testIgnoreLaterVersionClassDeserialization
GSON 1.x creates the empty string "" if the only element is skipped
GSON 2.x writes "null" if the only element is skipped
com.google.gson.functional.ObjectTest.testAnonymousLocalClassesSerialization
com.google.gson.functional.FieldExclusionTest.testInnerClassExclusion
com.google.gson.functional.VersioningTest.testIgnoreLaterVersionClassSerialization

View File

@ -443,7 +443,7 @@ public final class Gson {
*/
public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter();
toJson(toJsonTree(src, typeOfSrc), writer);
toJson(src, typeOfSrc, writer);
return writer.toString();
}
@ -486,8 +486,12 @@ public final class Gson {
* @since 1.2
*/
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
JsonElement jsonElement = toJsonTree(src, typeOfSrc);
toJson(jsonElement, writer);
try {
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
toJson(src, typeOfSrc, jsonWriter);
} catch (IOException e) {
throw new JsonIOException(e);
}
}
/**
@ -496,7 +500,22 @@ public final class Gson {
* @throws JsonIOException if there was a problem writing to the writer
*/
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {
toJson(toJsonTree(src, typeOfSrc), writer);
TypeAdapter<?> adapter = miniGson.getAdapter(TypeToken.get(typeOfSrc));
boolean oldLenient = writer.isLenient();
writer.setLenient(true);
boolean oldHtmlSafe = writer.isHtmlSafe();
writer.setHtmlSafe(htmlSafe);
boolean oldSerializeNulls = writer.getSerializeNulls();
writer.setSerializeNulls(serializeNulls);
try {
((TypeAdapter<Object>) adapter).write(writer, src);
} catch (IOException e) {
throw new JsonIOException(e);
} finally {
writer.setLenient(oldLenient);
writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
}
}
/**
@ -522,19 +541,29 @@ public final class Gson {
*/
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
try {
if (generateNonExecutableJson) {
writer.append(JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(Streams.writerForAppendable(writer));
if (prettyPrinting) {
jsonWriter.setIndent(" ");
}
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
toJson(jsonElement, jsonWriter);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Returns a new JSON writer configured for this GSON and with the non-execute
* prefix if that is configured.
*/
private JsonWriter newJsonWriter(Writer writer) throws IOException {
if (generateNonExecutableJson) {
writer.write(JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(writer);
if (prettyPrinting) {
jsonWriter.setIndent(" ");
}
jsonWriter.setSerializeNulls(serializeNulls);
return jsonWriter;
}
/**
* Writes the JSON for {@code jsonElement} to {@code writer}.
* @throws JsonIOException if there was a problem writing to the writer
@ -544,6 +573,8 @@ public final class Gson {
writer.setLenient(true);
boolean oldHtmlSafe = writer.isHtmlSafe();
writer.setHtmlSafe(htmlSafe);
boolean oldSerializeNulls = writer.getSerializeNulls();
writer.setSerializeNulls(serializeNulls);
try {
Streams.write(jsonElement, serializeNulls, writer);
} catch (IOException e) {
@ -551,6 +582,7 @@ public final class Gson {
} finally {
writer.setLenient(oldLenient);
writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
}
}

View File

@ -145,6 +145,10 @@ public class JsonWriter implements Closeable {
private boolean htmlSafe;
private String deferredName;
private boolean serializeNulls = true;
/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}.
* For best performance, ensure {@link Writer} is buffered; wrapping in
@ -217,6 +221,22 @@ public class JsonWriter implements Closeable {
return htmlSafe;
}
/**
* Sets whether object members are serialized when their value is null.
* This has no impact on array elements. The default is true.
*/
public final void setSerializeNulls(boolean serializeNulls) {
this.serializeNulls = serializeNulls;
}
/**
* Returns true if object members are serialized when their value is null.
* This has no impact on array elements. The default is true.
*/
public final boolean getSerializeNulls() {
return serializeNulls;
}
/**
* Begins encoding a new array. Each call to this method must be paired with
* a call to {@link #endArray}.
@ -224,6 +244,7 @@ public class JsonWriter implements Closeable {
* @return this writer.
*/
public JsonWriter beginArray() throws IOException {
writeDeferredName();
return open(JsonScope.EMPTY_ARRAY, "[");
}
@ -243,6 +264,7 @@ public class JsonWriter implements Closeable {
* @return this writer.
*/
public JsonWriter beginObject() throws IOException {
writeDeferredName();
return open(JsonScope.EMPTY_OBJECT, "{");
}
@ -276,6 +298,9 @@ public class JsonWriter implements Closeable {
if (context != nonempty && context != empty) {
throw new IllegalStateException("Nesting problem: " + stack);
}
if (deferredName != null) {
throw new IllegalStateException("Dangling name: " + deferredName);
}
stack.remove(stack.size() - 1);
if (context == nonempty) {
@ -309,11 +334,21 @@ public class JsonWriter implements Closeable {
if (name == null) {
throw new NullPointerException("name == null");
}
beforeName();
string(name);
if (deferredName != null) {
throw new IllegalStateException();
}
deferredName = name;
return this;
}
private void writeDeferredName() throws IOException {
if (deferredName != null) {
beforeName();
string(deferredName);
deferredName = null;
}
}
/**
* Encodes {@code value}.
*
@ -324,6 +359,7 @@ public class JsonWriter implements Closeable {
if (value == null) {
return nullValue();
}
writeDeferredName();
beforeValue(false);
string(value);
return this;
@ -335,6 +371,14 @@ public class JsonWriter implements Closeable {
* @return this writer.
*/
public JsonWriter nullValue() throws IOException {
if (deferredName != null) {
if (serializeNulls) {
writeDeferredName();
} else {
deferredName = null;
return this; // skip the name and the value
}
}
beforeValue(false);
out.write("null");
return this;
@ -346,6 +390,7 @@ public class JsonWriter implements Closeable {
* @return this writer.
*/
public JsonWriter value(boolean value) throws IOException {
writeDeferredName();
beforeValue(false);
out.write(value ? "true" : "false");
return this;
@ -362,6 +407,7 @@ public class JsonWriter implements Closeable {
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
writeDeferredName();
beforeValue(false);
out.append(Double.toString(value));
return this;
@ -373,6 +419,7 @@ public class JsonWriter implements Closeable {
* @return this writer.
*/
public JsonWriter value(long value) throws IOException {
writeDeferredName();
beforeValue(false);
out.write(Long.toString(value));
return this;
@ -390,6 +437,7 @@ public class JsonWriter implements Closeable {
return nullValue();
}
writeDeferredName();
String string = value.toString();
if (!lenient
&& (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {

View File

@ -55,7 +55,7 @@ public class FieldExclusionTest extends TestCase {
Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target);
assertEquals("", result);
assertEquals("null", result);
}
public void testDefaultNestedStaticClassIncluded() throws Exception {

View File

@ -267,7 +267,7 @@ public class ObjectTest extends TestCase {
}
public void testAnonymousLocalClassesSerialization() throws Exception {
assertEquals("", gson.toJson(new ClassWithNoFields() {
assertEquals("null", gson.toJson(new ClassWithNoFields() {
// empty anonymous class
}));
}

View File

@ -82,7 +82,7 @@ public class VersioningTest extends TestCase {
public void testIgnoreLaterVersionClassSerialization() {
Gson gson = builder.setVersion(1.0).create();
assertEquals("", gson.toJson(new Version1_2()));
assertEquals("null", gson.toJson(new Version1_2()));
}
public void testIgnoreLaterVersionClassDeserialization() {

View File

@ -24,6 +24,7 @@ public final class JsonElementWriterTest extends TestCase {
// TODO: more tests
// TODO: close support
// 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();