diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index ef8c81e378..8e699c2948 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -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; @@ -119,9 +120,9 @@ *
    *
  1. Use {@link #getAdapter(Class)} to obtain the adapter for the type to be serialized *
  2. When using an existing {@code JsonWriter}, manually apply the writer settings of this - * {@code Gson} instance listed by {@link #newJsonWriter(Writer)}.
    + * {@code Gson} instance listed by {@link #newJsonWriter(Appendable)}.
    * Otherwise, when not using an existing {@code JsonWriter}, use {@link - * #newJsonWriter(Writer)} to construct one. + * #newJsonWriter(Appendable)} to construct one. *
  3. Call {@link TypeAdapter#write(JsonWriter, Object)} *
* @@ -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}. @@ -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 @@ -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); @@ -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); @@ -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. * @@ -1049,9 +1060,9 @@ public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOExce *
  • {@link GsonBuilder#setFormattingStyle(FormattingStyle)} * */ - 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); diff --git a/gson/src/main/java/com/google/gson/JsonElement.java b/gson/src/main/java/com/google/gson/JsonElement.java index d280118de6..c02f18d6e9 100644 --- a/gson/src/main/java/com/google/gson/JsonElement.java +++ b/gson/src/main/java/com/google/gson/JsonElement.java @@ -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); diff --git a/gson/src/main/java/com/google/gson/TypeAdapter.java b/gson/src/main/java/com/google/gson/TypeAdapter.java index e33a839dbd..0e8d9b9610 100644 --- a/gson/src/main/java/com/google/gson/TypeAdapter.java +++ b/gson/src/main/java/com/google/gson/TypeAdapter.java @@ -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; @@ -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}. * @@ -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); } @@ -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); } diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java index fda2cf131c..e16e6a8894 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java +++ b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeWriter.java @@ -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) { diff --git a/gson/src/main/java/com/google/gson/stream/JsonWriter.java b/gson/src/main/java/com/google/gson/stream/JsonWriter.java index 42fc24cf55..c311dae9ed 100644 --- a/gson/src/main/java/com/google/gson/stream/JsonWriter.java +++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java @@ -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; @@ -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; @@ -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); } @@ -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; } @@ -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; } @@ -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; } @@ -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; } @@ -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; } @@ -675,7 +685,7 @@ public JsonWriter nullValue() throws IOException { } } beforeValue(); - out.write("null"); + out.append("null"); return this; } @@ -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)) { @@ -743,7 +761,7 @@ private static boolean alwaysCreatesValidJsonNumber(Class 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++) { @@ -762,15 +780,15 @@ 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 { @@ -778,9 +796,9 @@ private void newline() throws IOException { 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()); } } @@ -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."); } diff --git a/gson/src/test/java/com/google/gson/GsonBuilderTest.java b/gson/src/test/java/com/google/gson/GsonBuilderTest.java index 94cc8362d3..2c28a8b320 100644 --- a/gson/src/test/java/com/google/gson/GsonBuilderTest.java +++ b/gson/src/test/java/com/google/gson/GsonBuilderTest.java @@ -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; @@ -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); } @@ -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); } @@ -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 diff --git a/gson/src/test/java/com/google/gson/GsonTest.java b/gson/src/test/java/com/google/gson/GsonTest.java index 4798168984..2c49b89fd1 100644 --- a/gson/src/test/java/com/google/gson/GsonTest.java +++ b/gson/src/test/java/com/google/gson/GsonTest.java @@ -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; @@ -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"); @@ -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() diff --git a/gson/src/test/java/com/google/gson/MixedStreamTest.java b/gson/src/test/java/com/google/gson/MixedStreamTest.java index d65b36bb61..cb20c43519 100644 --- a/gson/src/test/java/com/google/gson/MixedStreamTest.java +++ b/gson/src/test/java/com/google/gson/MixedStreamTest.java @@ -24,7 +24,6 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.StringReader; -import java.io.StringWriter; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; @@ -54,8 +53,8 @@ public final class MixedStreamTest { @Test public void testWriteMixedStreamed() throws IOException { Gson gson = new Gson(); - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.setIndent(" "); @@ -64,7 +63,7 @@ public void testWriteMixedStreamed() throws IOException { gson.toJson(RED_MIATA, Car.class, jsonWriter); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo(CARS_JSON); + assertThat(writer.toString()).isEqualTo(CARS_JSON); } @Test @@ -102,7 +101,7 @@ public void testReadDoesNotMutateState() throws IOException { @Test public void testWriteDoesNotMutateState() throws IOException { Gson gson = new Gson(); - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.beginArray(); jsonWriter.setHtmlSafe(true); @@ -142,7 +141,7 @@ public void testReadClosed() throws IOException { @Test public void testWriteInvalidState() throws IOException { Gson gson = new Gson(); - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.beginObject(); var e = assertThrows( @@ -153,7 +152,7 @@ public void testWriteInvalidState() throws IOException { @Test public void testWriteClosed() throws IOException { Gson gson = new Gson(); - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.beginArray(); jsonWriter.endArray(); jsonWriter.close(); @@ -170,9 +169,9 @@ public void testWriteNulls() { NullPointerException.class, () -> gson.toJson(new JsonPrimitive("hello"), (JsonWriter) null)); - StringWriter stringWriter = new StringWriter(); - gson.toJson(null, new JsonWriter(stringWriter)); - assertThat(stringWriter.toString()).isEqualTo("null"); + StringBuilder writer = new StringBuilder(); + gson.toJson(null, new JsonWriter(writer)); + assertThat(writer.toString()).isEqualTo("null"); } @Test @@ -189,7 +188,7 @@ public void testWriteHtmlSafeWithEscaping() { List contents = Arrays.asList("<", ">", "&", "=", "'"); Type type = new TypeToken>() {}.getType(); - StringWriter writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); new Gson().toJson(contents, type, new JsonWriter(writer)); assertThat(writer.toString()) .isEqualTo("[\"\\u003c\",\"\\u003e\",\"\\u0026\",\"\\u003d\",\"\\u0027\"]"); @@ -200,7 +199,7 @@ public void testWriteHtmlSafeWithoutEscaping() { List contents = Arrays.asList("<", ">", "&", "=", "'"); Type type = new TypeToken>() {}.getType(); - StringWriter writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); new GsonBuilder().disableHtmlEscaping().create().toJson(contents, type, new JsonWriter(writer)); assertThat(writer.toString()).isEqualTo("[\"<\",\">\",\"&\",\"=\",\"'\"]"); } @@ -212,7 +211,7 @@ public void testWriteLenient() { Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, -0.0d, 0.5d, 0.0d); Type type = new TypeToken>() {}.getType(); - StringWriter writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); JsonWriter jsonWriter = new JsonWriter(writer); new GsonBuilder() .serializeSpecialFloatingPointValues() @@ -223,7 +222,7 @@ public void testWriteLenient() { var e = assertThrows( IllegalArgumentException.class, - () -> new Gson().toJson(doubles, type, new JsonWriter(new StringWriter()))); + () -> new Gson().toJson(doubles, type, new JsonWriter(new StringBuilder()))); assertThat(e) .hasMessageThat() .isEqualTo( diff --git a/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java index bba470774b..802f8962d9 100644 --- a/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java +++ b/gson/src/test/java/com/google/gson/functional/ParameterizedTypesTest.java @@ -32,8 +32,6 @@ import java.io.Reader; import java.io.Serializable; import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; @@ -152,7 +150,7 @@ public void testParameterizedTypesWithCustomDeserializer() { @Test public void testParameterizedTypesWithWriterSerialization() { - Writer writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); MyParameterizedType src = new MyParameterizedType<>(10); Type typeOfSrc = new TypeToken>() {}.getType(); gson.toJson(src, typeOfSrc, writer); diff --git a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java index 324ee0c426..2e259e9356 100644 --- a/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java +++ b/gson/src/test/java/com/google/gson/functional/ReadersWritersTest.java @@ -30,7 +30,6 @@ import java.io.IOException; import java.io.Reader; import java.io.StringReader; -import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.Type; import java.util.Arrays; @@ -54,7 +53,7 @@ public void setUp() throws Exception { @Test public void testWriterForSerialization() { - Writer writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); BagOfPrimitives src = new BagOfPrimitives(); gson.toJson(src, writer); assertThat(writer.toString()).isEqualTo(src.getExpectedJson()); @@ -70,7 +69,7 @@ public void testReaderForDeserialization() { @Test public void testTopLevelNullObjectSerializationWithWriter() { - StringWriter writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); gson.toJson(null, writer); assertThat(writer.toString()).isEqualTo("null"); } @@ -85,7 +84,7 @@ public void testTopLevelNullObjectDeserializationWithReader() { @Test public void testTopLevelNullObjectSerializationWithWriterAndSerializeNulls() { Gson gson = new GsonBuilder().serializeNulls().create(); - StringWriter writer = new StringWriter(); + StringBuilder writer = new StringBuilder(); gson.toJson(null, writer); assertThat(writer.toString()).isEqualTo("null"); } diff --git a/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java index fc401610e3..9f9eecf710 100644 --- a/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java +++ b/gson/src/test/java/com/google/gson/metrics/PerformanceTest.java @@ -22,7 +22,6 @@ import com.google.gson.JsonParseException; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; -import java.io.StringWriter; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; @@ -204,7 +203,7 @@ public void testSerializeClasses() { for (int i = 0; i < COLLECTION_SIZE; ++i) { c.list.add(new ClassWithField("element-" + i)); } - StringWriter w = new StringWriter(); + StringBuilder w = new StringBuilder(); long t1 = System.currentTimeMillis(); for (int i = 0; i < NUM_ITERATIONS; ++i) { gson.toJson(c, w); @@ -255,7 +254,7 @@ public void testSerializeExposedClasses() { c1.list.add(new ClassWithExposedField("element-" + i1)); } ClassWithListOfObjects c = c1; - StringWriter w = new StringWriter(); + StringBuilder w = new StringBuilder(); long t1 = System.currentTimeMillis(); for (int i = 0; i < NUM_ITERATIONS; ++i) { gson.toJson(c, w); diff --git a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java index fd171e880f..2c35dde72c 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -23,7 +23,6 @@ import com.google.gson.Strictness; import com.google.gson.internal.LazilyParsedNumber; import java.io.IOException; -import java.io.StringWriter; import java.math.BigDecimal; import java.math.BigInteger; import org.junit.Test; @@ -33,7 +32,7 @@ public final class JsonWriterTest { @Test public void testDefaultStrictness() throws IOException { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); jsonWriter.value(false); jsonWriter.close(); @@ -42,7 +41,7 @@ public void testDefaultStrictness() throws IOException { @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test public void testSetLenientTrue() throws IOException { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.setLenient(true); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LENIENT); jsonWriter.value(false); @@ -52,7 +51,7 @@ public void testSetLenientTrue() throws IOException { @SuppressWarnings("deprecation") // for JsonWriter.setLenient @Test public void testSetLenientFalse() throws IOException { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.setLenient(false); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.LEGACY_STRICT); jsonWriter.value(false); @@ -61,7 +60,7 @@ public void testSetLenientFalse() throws IOException { @Test public void testSetStrictness() throws IOException { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); jsonWriter.setStrictness(Strictness.STRICT); assertThat(jsonWriter.getStrictness()).isEqualTo(Strictness.STRICT); jsonWriter.value(false); @@ -70,7 +69,7 @@ public void testSetStrictness() throws IOException { @Test public void testSetStrictnessNull() throws IOException { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); assertThrows(NullPointerException.class, () -> jsonWriter.setStrictness(null)); jsonWriter.value(false); jsonWriter.close(); @@ -78,31 +77,31 @@ public void testSetStrictnessNull() throws IOException { @Test public void testTopLevelValueTypes() throws IOException { - StringWriter string1 = new StringWriter(); + StringBuilder string1 = new StringBuilder(); JsonWriter writer1 = new JsonWriter(string1); writer1.value(true); writer1.close(); assertThat(string1.toString()).isEqualTo("true"); - StringWriter string2 = new StringWriter(); + StringBuilder string2 = new StringBuilder(); JsonWriter writer2 = new JsonWriter(string2); writer2.nullValue(); writer2.close(); assertThat(string2.toString()).isEqualTo("null"); - StringWriter string3 = new StringWriter(); + StringBuilder string3 = new StringBuilder(); JsonWriter writer3 = new JsonWriter(string3); writer3.value(123); writer3.close(); assertThat(string3.toString()).isEqualTo("123"); - StringWriter string4 = new StringWriter(); + StringBuilder string4 = new StringBuilder(); JsonWriter writer4 = new JsonWriter(string4); writer4.value(123.4); writer4.close(); assertThat(string4.toString()).isEqualTo("123.4"); - StringWriter string5 = new StringWriter(); + StringBuilder string5 = new StringBuilder(); JsonWriter writert = new JsonWriter(string5); writert.value("a"); writert.close(); @@ -111,8 +110,8 @@ public void testTopLevelValueTypes() throws IOException { @Test public void testNameAsTopLevelValue() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); IllegalStateException e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("hello")); assertThat(e).hasMessageThat().isEqualTo("Please begin an object before writing a name."); @@ -126,8 +125,8 @@ public void testNameAsTopLevelValue() throws IOException { @Test public void testNameInArray() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); IllegalStateException e = @@ -141,13 +140,13 @@ public void testNameInArray() throws IOException { jsonWriter.endArray(); jsonWriter.close(); - assertThat(stringWriter.toString()).isEqualTo("[12]"); + assertThat(writer.toString()).isEqualTo("[12]"); } @Test public void testTwoNames() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a"); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("a")); @@ -156,8 +155,8 @@ public void testTwoNames() throws IOException { @Test public void testNameWithoutValue() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a"); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); @@ -166,8 +165,8 @@ public void testNameWithoutValue() throws IOException { @Test public void testValueWithoutName() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.value(true)); assertThat(e).hasMessageThat().isEqualTo("Nesting problem."); @@ -175,8 +174,8 @@ public void testValueWithoutName() throws IOException { @Test public void testMultipleTopLevelValues() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray().endArray(); IllegalStateException expected = @@ -186,8 +185,8 @@ public void testMultipleTopLevelValues() throws IOException { @Test public void testMultipleTopLevelValuesStrict() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.STRICT); jsonWriter.beginArray().endArray(); @@ -198,21 +197,21 @@ public void testMultipleTopLevelValuesStrict() throws IOException { @Test public void testMultipleTopLevelValuesLenient() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.setStrictness(Strictness.LENIENT); - writer.beginArray(); - writer.endArray(); - writer.beginArray(); - writer.endArray(); - writer.close(); - assertThat(stringWriter.toString()).isEqualTo("[][]"); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.setStrictness(Strictness.LENIENT); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); + assertThat(writer.toString()).isEqualTo("[][]"); } @Test public void testBadNestingObject() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.beginObject(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endArray()); @@ -221,8 +220,8 @@ public void testBadNestingObject() throws IOException { @Test public void testBadNestingArray() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.beginArray(); var e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); @@ -231,34 +230,34 @@ public void testBadNestingArray() throws IOException { @Test public void testNullName() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); assertThrows(NullPointerException.class, () -> jsonWriter.name(null)); } @Test public void testNullStringValue() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a"); jsonWriter.value((String) null); jsonWriter.endObject(); - assertThat(stringWriter.toString()).isEqualTo("{\"a\":null}"); + assertThat(writer.toString()).isEqualTo("{\"a\":null}"); } @Test public void testJsonValue() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a"); jsonWriter.jsonValue("{\"b\":true}"); jsonWriter.name("c"); jsonWriter.value(1); jsonWriter.endObject(); - assertThat(stringWriter.toString()).isEqualTo("{\"a\":{\"b\":true},\"c\":1}"); + assertThat(writer.toString()).isEqualTo("{\"a\":{\"b\":true},\"c\":1}"); } private static void assertNonFiniteFloatsExceptions(JsonWriter jsonWriter) throws IOException { @@ -285,15 +284,15 @@ private static void assertNonFiniteFloatsExceptions(JsonWriter jsonWriter) throw @Test public void testNonFiniteFloats() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); assertNonFiniteFloatsExceptions(jsonWriter); } @Test public void testNonFiniteFloatsWhenStrict() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteFloatsExceptions(jsonWriter); } @@ -322,15 +321,15 @@ private static void assertNonFiniteDoublesExceptions(JsonWriter jsonWriter) thro @Test public void testNonFiniteDoubles() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); assertNonFiniteDoublesExceptions(jsonWriter); } @Test public void testNonFiniteDoublesWhenStrict() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteDoublesExceptions(jsonWriter); } @@ -370,49 +369,49 @@ private static void assertNonFiniteNumbersExceptions(JsonWriter jsonWriter) thro @Test public void testNonFiniteNumbers() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); assertNonFiniteNumbersExceptions(jsonWriter); } @Test public void testNonFiniteNumbersWhenStrict() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.STRICT); assertNonFiniteNumbersExceptions(jsonWriter); } @Test public void testNonFiniteFloatsWhenLenient() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.LENIENT); jsonWriter.beginArray(); jsonWriter.value(Float.NaN); jsonWriter.value(Float.NEGATIVE_INFINITY); jsonWriter.value(Float.POSITIVE_INFINITY); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); + assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test public void testNonFiniteDoublesWhenLenient() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.LENIENT); jsonWriter.beginArray(); jsonWriter.value(Double.NaN); jsonWriter.value(Double.NEGATIVE_INFINITY); jsonWriter.value(Double.POSITIVE_INFINITY); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); + assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity]"); } @Test public void testNonFiniteNumbersWhenLenient() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setStrictness(Strictness.LENIENT); jsonWriter.beginArray(); jsonWriter.value(Double.valueOf(Double.NaN)); @@ -420,13 +419,13 @@ public void testNonFiniteNumbersWhenLenient() throws IOException { jsonWriter.value(Double.valueOf(Double.POSITIVE_INFINITY)); jsonWriter.value(new LazilyParsedNumber("Infinity")); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[NaN,-Infinity,Infinity,Infinity]"); + assertThat(writer.toString()).isEqualTo("[NaN,-Infinity,Infinity,Infinity]"); } @Test public void testFloats() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value(-0.0f); jsonWriter.value(1.0f); @@ -440,7 +439,7 @@ public void testFloats() throws IOException { jsonWriter.value((float) Math.E); jsonWriter.endArray(); jsonWriter.close(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo( "[-0.0," + "1.0," @@ -456,8 +455,8 @@ public void testFloats() throws IOException { @Test public void testDoubles() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value(-0.0); jsonWriter.value(1.0); @@ -470,7 +469,7 @@ public void testDoubles() throws IOException { jsonWriter.value(Math.E); jsonWriter.endArray(); jsonWriter.close(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo( "[-0.0," + "1.0," @@ -485,8 +484,8 @@ public void testDoubles() throws IOException { @Test public void testLongs() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value(0); jsonWriter.value(1); @@ -495,14 +494,14 @@ public void testLongs() throws IOException { jsonWriter.value(Long.MAX_VALUE); jsonWriter.endArray(); jsonWriter.close(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo("[0," + "1," + "-1," + "-9223372036854775808," + "9223372036854775807]"); } @Test public void testNumbers() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value(new BigInteger("0")); jsonWriter.value(new BigInteger("9223372036854775808")); @@ -510,7 +509,7 @@ public void testNumbers() throws IOException { jsonWriter.value(new BigDecimal("3.141592653589793238462643383")); jsonWriter.endArray(); jsonWriter.close(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo( "[0," + "9223372036854775808," @@ -543,13 +542,13 @@ public void testNumbersCustomClass() throws IOException { }; for (String validNumber : validNumbers) { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.value(new LazilyParsedNumber(validNumber)); jsonWriter.close(); - assertThat(stringWriter.toString()).isEqualTo(validNumber); + assertThat(writer.toString()).isEqualTo(validNumber); } } @@ -583,7 +582,7 @@ public void testMalformedNumbers() throws IOException { }; for (String malformedNumber : malformedNumbers) { - JsonWriter jsonWriter = new JsonWriter(new StringWriter()); + JsonWriter jsonWriter = new JsonWriter(new StringBuilder()); var e = assertThrows( IllegalArgumentException.class, @@ -599,41 +598,41 @@ public void testMalformedNumbers() throws IOException { @Test public void testBooleans() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value(true); jsonWriter.value(false); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[true,false]"); + assertThat(writer.toString()).isEqualTo("[true,false]"); } @Test public void testBoxedBooleans() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value((Boolean) true); jsonWriter.value((Boolean) false); jsonWriter.value((Boolean) null); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[true,false,null]"); + assertThat(writer.toString()).isEqualTo("[true,false,null]"); } @Test public void testNulls() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.nullValue(); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[null]"); + assertThat(writer.toString()).isEqualTo("[null]"); } @Test public void testStrings() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value("a"); jsonWriter.value("a\""); @@ -654,7 +653,7 @@ public void testStrings() throws IOException { jsonWriter.value("\0"); jsonWriter.value("\u0019"); jsonWriter.endArray(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo( "[\"a\"," + "\"a\\\"\"," @@ -678,38 +677,38 @@ public void testStrings() throws IOException { @Test public void testUnicodeLineBreaksEscaped() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.value("\u2028 \u2029"); jsonWriter.endArray(); // JSON specification does not require that they are escaped, but Gson escapes them for // compatibility with JavaScript where they are considered line breaks - assertThat(stringWriter.toString()).isEqualTo("[\"\\u2028 \\u2029\"]"); + assertThat(writer.toString()).isEqualTo("[\"\\u2028 \\u2029\"]"); } @Test public void testEmptyArray() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.endArray(); - assertThat(stringWriter.toString()).isEqualTo("[]"); + assertThat(writer.toString()).isEqualTo("[]"); } @Test public void testEmptyObject() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.endObject(); - assertThat(stringWriter.toString()).isEqualTo("{}"); + assertThat(writer.toString()).isEqualTo("{}"); } @Test public void testObjectsInArrays() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginArray(); jsonWriter.beginObject(); jsonWriter.name("a").value(5); @@ -720,14 +719,13 @@ public void testObjectsInArrays() throws IOException { jsonWriter.name("d").value(true); jsonWriter.endObject(); jsonWriter.endArray(); - assertThat(stringWriter.toString()) - .isEqualTo("[{\"a\":5,\"b\":false}," + "{\"c\":6,\"d\":true}]"); + assertThat(writer.toString()).isEqualTo("[{\"a\":5,\"b\":false}," + "{\"c\":6,\"d\":true}]"); } @Test public void testArraysInObjects() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a"); jsonWriter.beginArray(); @@ -740,26 +738,26 @@ public void testArraysInObjects() throws IOException { jsonWriter.value(true); jsonWriter.endArray(); jsonWriter.endObject(); - assertThat(stringWriter.toString()).isEqualTo("{\"a\":[5,false]," + "\"b\":[6,true]}"); + assertThat(writer.toString()).isEqualTo("{\"a\":[5,false]," + "\"b\":[6,true]}"); } @Test public void testDeepNestingArrays() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); for (int i = 0; i < 20; i++) { jsonWriter.beginArray(); } for (int i = 0; i < 20; i++) { jsonWriter.endArray(); } - assertThat(stringWriter.toString()).isEqualTo("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]"); + assertThat(writer.toString()).isEqualTo("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]"); } @Test public void testDeepNestingObjects() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); for (int i = 0; i < 20; i++) { jsonWriter.name("a"); @@ -769,7 +767,7 @@ public void testDeepNestingObjects() throws IOException { jsonWriter.endObject(); } jsonWriter.endObject(); - assertThat(stringWriter.toString()) + assertThat(writer.toString()) .isEqualTo( "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":" + "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{" @@ -778,20 +776,20 @@ public void testDeepNestingObjects() throws IOException { @Test public void testRepeatedName() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.beginObject(); jsonWriter.name("a").value(true); jsonWriter.name("a").value(false); jsonWriter.endObject(); // JsonWriter doesn't attempt to detect duplicate names - assertThat(stringWriter.toString()).isEqualTo("{\"a\":true,\"a\":false}"); + assertThat(writer.toString()).isEqualTo("{\"a\":true,\"a\":false}"); } @Test public void testPrettyPrintObject() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setIndent(" "); jsonWriter.beginObject(); @@ -824,13 +822,13 @@ public void testPrettyPrintObject() throws IOException { + " \"i\": 9.0\n" + " }\n" + "}"; - assertThat(stringWriter.toString()).isEqualTo(expected); + assertThat(writer.toString()).isEqualTo(expected); } @Test public void testPrettyPrintArray() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setIndent(" "); jsonWriter.beginArray(); @@ -863,82 +861,82 @@ public void testPrettyPrintArray() throws IOException { + " 9.0\n" + " ]\n" + "]"; - assertThat(stringWriter.toString()).isEqualTo(expected); + assertThat(writer.toString()).isEqualTo(expected); } @Test public void testClosedWriterThrowsOnStructure() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.beginArray(); - writer.endArray(); - writer.close(); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); String expectedMessage = "JsonWriter is closed."; - var e = assertThrows(IllegalStateException.class, () -> writer.beginArray()); + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.beginArray()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); - e = assertThrows(IllegalStateException.class, () -> writer.endArray()); + e = assertThrows(IllegalStateException.class, () -> jsonWriter.endArray()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); - e = assertThrows(IllegalStateException.class, () -> writer.beginObject()); + e = assertThrows(IllegalStateException.class, () -> jsonWriter.beginObject()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); - e = assertThrows(IllegalStateException.class, () -> writer.endObject()); + e = assertThrows(IllegalStateException.class, () -> jsonWriter.endObject()); assertThat(e).hasMessageThat().isEqualTo(expectedMessage); } @Test public void testClosedWriterThrowsOnName() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.beginArray(); - writer.endArray(); - writer.close(); - var e = assertThrows(IllegalStateException.class, () -> writer.name("a")); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.name("a")); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testClosedWriterThrowsOnValue() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.beginArray(); - writer.endArray(); - writer.close(); - var e = assertThrows(IllegalStateException.class, () -> writer.value("a")); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); + var e = assertThrows(IllegalStateException.class, () -> jsonWriter.value("a")); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testClosedWriterThrowsOnFlush() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.beginArray(); - writer.endArray(); - writer.close(); - var e = assertThrows(IllegalStateException.class, () -> writer.flush()); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); + var e = assertThrows(IllegalStateException.class, jsonWriter::flush); assertThat(e).hasMessageThat().isEqualTo("JsonWriter is closed."); } @Test public void testWriterCloseIsIdempotent() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter writer = new JsonWriter(stringWriter); - writer.beginArray(); - writer.endArray(); - writer.close(); - assertThat(stringWriter.toString()).isEqualTo("[]"); - writer.close(); - assertThat(stringWriter.toString()).isEqualTo("[]"); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); + jsonWriter.beginArray(); + jsonWriter.endArray(); + jsonWriter.close(); + assertThat(writer.toString()).isEqualTo("[]"); + jsonWriter.close(); + assertThat(writer.toString()).isEqualTo("[]"); } @Test public void testSetGetFormattingStyle() throws IOException { String lineSeparator = "\r\n"; - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); // Default should be FormattingStyle.COMPACT assertThat(jsonWriter.getFormattingStyle()).isSameInstanceAs(FormattingStyle.COMPACT); jsonWriter.setFormattingStyle( @@ -958,15 +956,15 @@ public void testSetGetFormattingStyle() throws IOException { + " \t 5.0,\r\n" // + " \t null\r\n" // + "]"; - assertThat(stringWriter.toString()).isEqualTo(expected); + assertThat(writer.toString()).isEqualTo(expected); assertThat(jsonWriter.getFormattingStyle().getNewline()).isEqualTo(lineSeparator); } @Test public void testIndentOverwritesFormattingStyle() throws IOException { - StringWriter stringWriter = new StringWriter(); - JsonWriter jsonWriter = new JsonWriter(stringWriter); + StringBuilder writer = new StringBuilder(); + JsonWriter jsonWriter = new JsonWriter(writer); jsonWriter.setFormattingStyle(FormattingStyle.COMPACT); // Should overwrite formatting style jsonWriter.setIndent(" "); @@ -986,6 +984,6 @@ public void testIndentOverwritesFormattingStyle() throws IOException { + " 2\n" // + " ]\n" // + "}"; - assertThat(stringWriter.toString()).isEqualTo(expected); + assertThat(writer.toString()).isEqualTo(expected); } }