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 GSON 2.x sets fields of the requested type only
com.google.gson.functional.InstanceCreatorTest.testInstanceCreatorReturnsSubTypeForField com.google.gson.functional.InstanceCreatorTest.testInstanceCreatorReturnsSubTypeForField
GSON 1.x applies different rules for versioning for classes vs fields. So, if you deserialize a 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). 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. 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. GSON 2.x returns null for the top-level class.
com.google.gson.functional.VersioningTest.testIgnoreLaterVersionClassDeserialization 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) { public String toJson(Object src, Type typeOfSrc) {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
toJson(toJsonTree(src, typeOfSrc), writer); toJson(src, typeOfSrc, writer);
return writer.toString(); return writer.toString();
} }
@ -486,8 +486,12 @@ public final class Gson {
* @since 1.2 * @since 1.2
*/ */
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException { public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
JsonElement jsonElement = toJsonTree(src, typeOfSrc); try {
toJson(jsonElement, writer); 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 * @throws JsonIOException if there was a problem writing to the writer
*/ */
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException { 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 { public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
try { try {
if (generateNonExecutableJson) { JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
writer.append(JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(Streams.writerForAppendable(writer));
if (prettyPrinting) {
jsonWriter.setIndent(" ");
}
toJson(jsonElement, jsonWriter); toJson(jsonElement, jsonWriter);
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(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}. * Writes the JSON for {@code jsonElement} to {@code writer}.
* @throws JsonIOException if there was a problem writing to the writer * @throws JsonIOException if there was a problem writing to the writer
@ -544,6 +573,8 @@ public final class Gson {
writer.setLenient(true); writer.setLenient(true);
boolean oldHtmlSafe = writer.isHtmlSafe(); boolean oldHtmlSafe = writer.isHtmlSafe();
writer.setHtmlSafe(htmlSafe); writer.setHtmlSafe(htmlSafe);
boolean oldSerializeNulls = writer.getSerializeNulls();
writer.setSerializeNulls(serializeNulls);
try { try {
Streams.write(jsonElement, serializeNulls, writer); Streams.write(jsonElement, serializeNulls, writer);
} catch (IOException e) { } catch (IOException e) {
@ -551,6 +582,7 @@ public final class Gson {
} finally { } finally {
writer.setLenient(oldLenient); writer.setLenient(oldLenient);
writer.setHtmlSafe(oldHtmlSafe); writer.setHtmlSafe(oldHtmlSafe);
writer.setSerializeNulls(oldSerializeNulls);
} }
} }

View File

@ -145,6 +145,10 @@ public class JsonWriter implements Closeable {
private boolean htmlSafe; private boolean htmlSafe;
private String deferredName;
private boolean serializeNulls = true;
/** /**
* Creates a new instance that writes a JSON-encoded stream to {@code out}. * Creates a new instance that writes a JSON-encoded stream to {@code out}.
* For best performance, ensure {@link Writer} is buffered; wrapping in * For best performance, ensure {@link Writer} is buffered; wrapping in
@ -217,6 +221,22 @@ public class JsonWriter implements Closeable {
return htmlSafe; 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 * Begins encoding a new array. Each call to this method must be paired with
* a call to {@link #endArray}. * a call to {@link #endArray}.
@ -224,6 +244,7 @@ public class JsonWriter implements Closeable {
* @return this writer. * @return this writer.
*/ */
public JsonWriter beginArray() throws IOException { public JsonWriter beginArray() throws IOException {
writeDeferredName();
return open(JsonScope.EMPTY_ARRAY, "["); return open(JsonScope.EMPTY_ARRAY, "[");
} }
@ -243,6 +264,7 @@ public class JsonWriter implements Closeable {
* @return this writer. * @return this writer.
*/ */
public JsonWriter beginObject() throws IOException { public JsonWriter beginObject() throws IOException {
writeDeferredName();
return open(JsonScope.EMPTY_OBJECT, "{"); return open(JsonScope.EMPTY_OBJECT, "{");
} }
@ -276,6 +298,9 @@ public class JsonWriter implements Closeable {
if (context != nonempty && context != empty) { if (context != nonempty && context != empty) {
throw new IllegalStateException("Nesting problem: " + stack); throw new IllegalStateException("Nesting problem: " + stack);
} }
if (deferredName != null) {
throw new IllegalStateException("Dangling name: " + deferredName);
}
stack.remove(stack.size() - 1); stack.remove(stack.size() - 1);
if (context == nonempty) { if (context == nonempty) {
@ -309,11 +334,21 @@ public class JsonWriter implements Closeable {
if (name == null) { if (name == null) {
throw new NullPointerException("name == null"); throw new NullPointerException("name == null");
} }
beforeName(); if (deferredName != null) {
string(name); throw new IllegalStateException();
}
deferredName = name;
return this; return this;
} }
private void writeDeferredName() throws IOException {
if (deferredName != null) {
beforeName();
string(deferredName);
deferredName = null;
}
}
/** /**
* Encodes {@code value}. * Encodes {@code value}.
* *
@ -324,6 +359,7 @@ public class JsonWriter implements Closeable {
if (value == null) { if (value == null) {
return nullValue(); return nullValue();
} }
writeDeferredName();
beforeValue(false); beforeValue(false);
string(value); string(value);
return this; return this;
@ -335,6 +371,14 @@ public class JsonWriter implements Closeable {
* @return this writer. * @return this writer.
*/ */
public JsonWriter nullValue() throws IOException { public JsonWriter nullValue() throws IOException {
if (deferredName != null) {
if (serializeNulls) {
writeDeferredName();
} else {
deferredName = null;
return this; // skip the name and the value
}
}
beforeValue(false); beforeValue(false);
out.write("null"); out.write("null");
return this; return this;
@ -346,6 +390,7 @@ public class JsonWriter implements Closeable {
* @return this writer. * @return this writer.
*/ */
public JsonWriter value(boolean value) throws IOException { public JsonWriter value(boolean value) throws IOException {
writeDeferredName();
beforeValue(false); beforeValue(false);
out.write(value ? "true" : "false"); out.write(value ? "true" : "false");
return this; return this;
@ -362,6 +407,7 @@ public class JsonWriter implements Closeable {
if (Double.isNaN(value) || Double.isInfinite(value)) { if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value); throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
} }
writeDeferredName();
beforeValue(false); beforeValue(false);
out.append(Double.toString(value)); out.append(Double.toString(value));
return this; return this;
@ -373,6 +419,7 @@ public class JsonWriter implements Closeable {
* @return this writer. * @return this writer.
*/ */
public JsonWriter value(long value) throws IOException { public JsonWriter value(long value) throws IOException {
writeDeferredName();
beforeValue(false); beforeValue(false);
out.write(Long.toString(value)); out.write(Long.toString(value));
return this; return this;
@ -390,6 +437,7 @@ public class JsonWriter implements Closeable {
return nullValue(); return nullValue();
} }
writeDeferredName();
String string = value.toString(); String string = value.toString();
if (!lenient if (!lenient
&& (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) { && (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(); Gson gson = new GsonBuilder().disableInnerClassSerialization().create();
Outer.Inner target = outer.new Inner(VALUE); Outer.Inner target = outer.new Inner(VALUE);
String result = gson.toJson(target); String result = gson.toJson(target);
assertEquals("", result); assertEquals("null", result);
} }
public void testDefaultNestedStaticClassIncluded() throws Exception { public void testDefaultNestedStaticClassIncluded() throws Exception {

View File

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

View File

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

View File

@ -24,6 +24,7 @@ public final class JsonElementWriterTest extends TestCase {
// TODO: more tests // TODO: more tests
// TODO: close support // TODO: close support
// TODO: figure out what should be returned by an empty writer // TODO: figure out what should be returned by an empty writer
// TODO: test when serialize nulls is false
public void testArray() throws IOException { public void testArray() throws IOException {
JsonElementWriter writer = new JsonElementWriter(); JsonElementWriter writer = new JsonElementWriter();