Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions gson/src/main/java/com/google/gson/Gson.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.gson;

import com.google.errorprone.annotations.InlineMe;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.internal.Excluder;
Expand Down Expand Up @@ -119,9 +120,9 @@
* <ol>
* <li>Use {@link #getAdapter(Class)} to obtain the adapter for the type to be serialized
* <li>When using an existing {@code JsonWriter}, manually apply the writer settings of this
* {@code Gson} instance listed by {@link #newJsonWriter(Writer)}.<br>
* {@code Gson} instance listed by {@link #newJsonWriter(Appendable)}.<br>
* Otherwise, when not using an existing {@code JsonWriter}, use {@link
* #newJsonWriter(Writer)} to construct one.
* #newJsonWriter(Appendable)} to construct one.
* <li>Call {@link TypeAdapter#write(JsonWriter, Object)}
* </ol>
*
Expand Down Expand Up @@ -809,8 +810,8 @@ public JsonElement toJsonTree(Object src, Type typeOfSrc) {
* the generic type information because of the Type Erasure feature of Java. Note that this method
* works fine if any of the object fields are of generic type, just the object itself should not
* be of a generic type. If the object is of generic type, use {@link #toJson(Object, Type)}
* instead. If you want to write out the object to a {@link Writer}, use {@link #toJson(Object,
* Appendable)} instead.
* instead. If you want to write out the object to an {@link Appendable}, use {@link
* #toJson(Object, Appendable)} instead.
*
* @param src the object for which JSON representation is to be created
* @return JSON representation of {@code src}.
Expand All @@ -828,7 +829,7 @@ public String toJson(Object src) {
* This method serializes the specified object, including those of generic types, into its
* equivalent JSON representation. This method must be used if the specified object is a generic
* type. For non-generic objects, use {@link #toJson(Object)} instead. If you want to write out
* the object to a {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
* the object to an {@link Appendable}, use {@link #toJson(Object, Type, Appendable)} instead.
*
* @param src the object for which JSON representation is to be created
* @param typeOfSrc The specific genericized type of src. You can obtain this type by using the
Expand Down Expand Up @@ -894,7 +895,7 @@ public void toJson(Object src, Appendable writer) throws JsonIOException {
*/
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {
try {
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
JsonWriter jsonWriter = newJsonWriter(writer);
toJson(src, typeOfSrc, jsonWriter);
} catch (IOException e) {
throw new JsonIOException(e);
Expand Down Expand Up @@ -976,7 +977,7 @@ public String toJson(JsonElement jsonElement) {
*/
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {
try {
JsonWriter jsonWriter = newJsonWriter(Streams.writerForAppendable(writer));
JsonWriter jsonWriter = newJsonWriter(writer);
toJson(jsonElement, jsonWriter);
} catch (IOException e) {
throw new JsonIOException(e);
Expand Down Expand Up @@ -1032,6 +1033,16 @@ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOExce
}
}

/**
* For compatibility only!
*
* @see Gson#newJsonWriter(Appendable)
*/
@InlineMe(replacement = "this.newJsonWriter((Appendable) writer)")
public JsonWriter newJsonWriter(Writer writer) throws IOException {
return newJsonWriter((Appendable) writer);
}

/**
* Returns a new JSON writer configured for the settings on this Gson instance.
*
Expand All @@ -1049,9 +1060,9 @@ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOExce
* <li>{@link GsonBuilder#setFormattingStyle(FormattingStyle)}
* </ul>
*/
public JsonWriter newJsonWriter(Writer writer) throws IOException {
public JsonWriter newJsonWriter(Appendable writer) throws IOException {
if (generateNonExecutableJson) {
writer.write(JSON_NON_EXECUTABLE_PREFIX);
writer.append(JSON_NON_EXECUTABLE_PREFIX);
}
JsonWriter jsonWriter = new JsonWriter(writer);
jsonWriter.setFormattingStyle(formattingStyle);
Expand Down
2 changes: 1 addition & 1 deletion gson/src/main/java/com/google/gson/JsonElement.java
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ public short getAsShort() {
public String toString() {
try {
StringBuilder stringBuilder = new StringBuilder();
JsonWriter jsonWriter = new JsonWriter(Streams.writerForAppendable(stringBuilder));
JsonWriter jsonWriter = new JsonWriter(stringBuilder);
// Make writer lenient because toString() must not fail, even if for example JsonPrimitive
// contains NaN
jsonWriter.setStrictness(Strictness.LENIENT);
Expand Down
16 changes: 13 additions & 3 deletions gson/src/main/java/com/google/gson/TypeAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.google.gson;

import com.google.gson.internal.Streams;
import com.google.errorprone.annotations.InlineMe;
import com.google.gson.internal.bind.JsonTreeReader;
import com.google.gson.internal.bind.JsonTreeWriter;
import com.google.gson.stream.JsonReader;
Expand Down Expand Up @@ -129,6 +129,16 @@ public TypeAdapter() {}
*/
public abstract void write(JsonWriter out, T value) throws IOException;

/**
* For compatibility only!
*
* @see TypeAdapter#toJson(Appendable, Object)
*/
@InlineMe(replacement = "this.toJson((Appendable) out, value)")
public final void toJson(Writer out, T value) throws IOException {
toJson((Appendable) out, value);
}

/**
* Converts {@code value} to a JSON document and writes it to {@code out}.
*
Expand All @@ -139,7 +149,7 @@ public TypeAdapter() {}
* @param value the Java object to convert. May be {@code null}.
* @since 2.2
*/
public final void toJson(Writer out, T value) throws IOException {
public final void toJson(Appendable out, T value) throws IOException {
JsonWriter writer = new JsonWriter(out);
write(writer, value);
}
Expand All @@ -159,7 +169,7 @@ public final void toJson(Writer out, T value) throws IOException {
public final String toJson(T value) {
StringBuilder stringBuilder = new StringBuilder();
try {
toJson(Streams.writerForAppendable(stringBuilder), value);
toJson(stringBuilder, value);
} catch (IOException e) {
throw new JsonIOException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@

/** This writer creates a JsonElement. */
public final class JsonTreeWriter extends JsonWriter {
private static final Writer UNWRITABLE_WRITER =
private static final Appendable UNWRITABLE_WRITER =
new Writer() {
@Override
public void write(char[] buffer, int offset, int counter) {
Expand Down
56 changes: 37 additions & 19 deletions gson/src/main/java/com/google/gson/stream/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import static com.google.gson.stream.JsonScope.NONEMPTY_OBJECT;

import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.InlineMe;
import com.google.gson.FormattingStyle;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Expand Down Expand Up @@ -200,7 +201,7 @@ public class JsonWriter implements Closeable, Flushable {
}

/** The JSON output destination */
private final Writer out;
private final Appendable out;

private int[] stack = new int[32];
private int stackSize = 0;
Expand Down Expand Up @@ -229,7 +230,16 @@ public class JsonWriter implements Closeable, Flushable {
* ensure {@link Writer} is buffered; wrapping in {@link java.io.BufferedWriter BufferedWriter} if
* necessary.
*/
@InlineMe(replacement = "this((Appendable) out)")
public JsonWriter(Writer out) {
this((Appendable) out);
}

/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}. For best performance,
* ensure the {@link Appendable} is buffered if there are actual IO operations.
*/
public JsonWriter(Appendable out) {
this.out = Objects.requireNonNull(out, "out == null");
setFormattingStyle(FormattingStyle.COMPACT);
}
Expand Down Expand Up @@ -447,7 +457,7 @@ public JsonWriter endObject() throws IOException {
private JsonWriter openScope(int empty, char openBracket) throws IOException {
beforeValue();
push(empty);
out.write(openBracket);
out.append(openBracket);
return this;
}

Expand All @@ -466,7 +476,7 @@ private JsonWriter closeScope(int empty, int nonempty, char closeBracket) throws
if (context == nonempty) {
newline();
}
out.write(closeBracket);
out.append(closeBracket);
return this;
}

Expand Down Expand Up @@ -544,7 +554,7 @@ public JsonWriter value(String value) throws IOException {
public JsonWriter value(boolean value) throws IOException {
writeDeferredName();
beforeValue();
out.write(value ? "true" : "false");
out.append(value ? "true" : "false");
return this;
}

Expand All @@ -561,7 +571,7 @@ public JsonWriter value(Boolean value) throws IOException {
}
writeDeferredName();
beforeValue();
out.write(value ? "true" : "false");
out.append(value ? "true" : "false");
return this;
}

Expand Down Expand Up @@ -615,7 +625,7 @@ public JsonWriter value(double value) throws IOException {
public JsonWriter value(long value) throws IOException {
writeDeferredName();
beforeValue();
out.write(Long.toString(value));
out.append(Long.toString(value));
return this;
}

Expand Down Expand Up @@ -675,7 +685,7 @@ public JsonWriter nullValue() throws IOException {
}
}
beforeValue();
out.write("null");
out.append("null");
return this;
}

Expand All @@ -701,24 +711,32 @@ public JsonWriter jsonValue(String value) throws IOException {
}

/**
* Ensures all buffered data is written to the underlying {@link Writer} and flushes that writer.
* Ensures all buffered data is written to the underlying {@link Appendable} and flushes it if it
* is an instance of {@link Flushable}.
*
* @throws IllegalStateException if this writer is closed.
*/
@Override
public void flush() throws IOException {
if (stackSize == 0) {
throw new IllegalStateException("JsonWriter is closed.");
}
out.flush();
if (out instanceof Flushable) {
((Flushable) out).flush();
}
}

/**
* Flushes and closes this writer and the underlying {@link Writer}.
* Flushes and closes this writer and the underlying {@link Appendable} if it is an instance of
* {@link Closeable}.
*
* @throws IOException if the JSON document is incomplete.
*/
@Override
public void close() throws IOException {
out.close();
if (out instanceof Closeable) {
((Closeable) out).close();
}

int size = stackSize;
if (size > 1 || (size == 1 && stack[size - 1] != NONEMPTY_DOCUMENT)) {
Expand All @@ -743,7 +761,7 @@ private static boolean alwaysCreatesValidJsonNumber(Class<? extends Number> c) {

private void string(String value) throws IOException {
String[] replacements = htmlSafe ? HTML_SAFE_REPLACEMENT_CHARS : REPLACEMENT_CHARS;
out.write('\"');
out.append('\"');
int last = 0;
int length = value.length();
for (int i = 0; i < length; i++) {
Expand All @@ -762,25 +780,25 @@ private void string(String value) throws IOException {
continue;
}
if (last < i) {
out.write(value, last, i - last);
out.append(value, last, i);
}
out.write(replacement);
out.append(replacement);
last = i + 1;
}
if (last < length) {
out.write(value, last, length - last);
out.append(value, last, length);
}
out.write('\"');
out.append('\"');
}

private void newline() throws IOException {
if (usesEmptyNewlineAndIndent) {
return;
}

out.write(formattingStyle.getNewline());
out.append(formattingStyle.getNewline());
for (int i = 1, size = stackSize; i < size; i++) {
out.write(formattingStyle.getIndent());
out.append(formattingStyle.getIndent());
}
}

Expand All @@ -791,7 +809,7 @@ private void newline() throws IOException {
private void beforeName() throws IOException {
int context = peek();
if (context == NONEMPTY_OBJECT) { // first in object
out.write(formattedComma);
out.append(formattedComma);
} else if (context != EMPTY_OBJECT) { // not in an object!
throw new IllegalStateException("Nesting problem.");
}
Expand Down
7 changes: 3 additions & 4 deletions gson/src/test/java/com/google/gson/GsonBuilderTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.text.DateFormat;
Expand Down Expand Up @@ -222,7 +221,7 @@ public void testDefaultStrictness() throws IOException {
Gson gson = builder.create();
assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness())
.isEqualTo(Strictness.LEGACY_STRICT);
assertThat(gson.newJsonWriter(new StringWriter()).getStrictness())
assertThat(gson.newJsonWriter(new StringBuilder()).getStrictness())
.isEqualTo(Strictness.LEGACY_STRICT);
}

Expand All @@ -234,7 +233,7 @@ public void testSetLenient() throws IOException {
Gson gson = builder.create();
assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness())
.isEqualTo(Strictness.LENIENT);
assertThat(gson.newJsonWriter(new StringWriter()).getStrictness())
assertThat(gson.newJsonWriter(new StringBuilder()).getStrictness())
.isEqualTo(Strictness.LENIENT);
}

Expand All @@ -245,7 +244,7 @@ public void testSetStrictness() throws IOException {
builder.setStrictness(strictness);
Gson gson = builder.create();
assertThat(gson.newJsonReader(new StringReader("{}")).getStrictness()).isEqualTo(strictness);
assertThat(gson.newJsonWriter(new StringWriter()).getStrictness()).isEqualTo(strictness);
assertThat(gson.newJsonWriter(new StringBuilder()).getStrictness()).isEqualTo(strictness);
}

@Test
Expand Down
5 changes: 2 additions & 3 deletions gson/src/test/java/com/google/gson/GsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import com.google.gson.stream.MalformedJsonException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -455,7 +454,7 @@ public int hashCode() {

@Test
public void testNewJsonWriter_Default() throws IOException {
StringWriter writer = new StringWriter();
StringBuilder writer = new StringBuilder();
JsonWriter jsonWriter = new Gson().newJsonWriter(writer);
jsonWriter.beginObject();
jsonWriter.name("test");
Expand All @@ -475,7 +474,7 @@ public void testNewJsonWriter_Default() throws IOException {
@SuppressWarnings({"deprecation", "InlineMeInliner"}) // for GsonBuilder.setLenient
@Test
public void testNewJsonWriter_Custom() throws IOException {
StringWriter writer = new StringWriter();
StringBuilder writer = new StringBuilder();
JsonWriter jsonWriter =
new GsonBuilder()
.disableHtmlEscaping()
Expand Down
Loading