From f7abd59a3b349d5c926507705f439afff54ed301 Mon Sep 17 00:00:00 2001 From: Adam Tanner Date: Sun, 19 Jul 2015 12:46:26 -0700 Subject: JsonWriter#jsonValue writes raw JSON values. Add a jsonValue(String value) method that takes a raw JSON string that can be used to write the string directly to the underlying writer without modification. The intended use case for this is when building JSON that contains a pre-serialized JSON string as a value in an object or array. --- .../main/java/com/google/gson/stream/JsonWriter.java | 17 +++++++++++++++++ .../java/com/google/gson/stream/JsonWriterTest.java | 12 ++++++++++++ 2 files changed, 29 insertions(+) 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 6a935ddb..839295d4 100644 --- a/gson/src/main/java/com/google/gson/stream/JsonWriter.java +++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java @@ -420,6 +420,23 @@ public class JsonWriter implements Closeable, Flushable { return this; } + /** + * Writes {@code value} directly to the writer without quoting or + * escaping. + * + * @param value the literal string value, or null to encode a null literal. + * @return this writer. + */ + public JsonWriter jsonValue(String value) throws IOException { + if (value == null) { + return nullValue(); + } + writeDeferredName(); + beforeValue(false); + out.append(value); + return this; + } + /** * Encodes {@code null}. * 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 24a1b703..4cfd55a7 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -126,6 +126,18 @@ public final class JsonWriterTest extends TestCase { assertEquals("{\"a\":null}", stringWriter.toString()); } + public void testJsonValue() throws IOException { + StringWriter stringWriter = new StringWriter(); + JsonWriter jsonWriter = new JsonWriter(stringWriter); + jsonWriter.beginObject(); + jsonWriter.name("a"); + jsonWriter.jsonValue("{\"b\":true}"); + jsonWriter.name("c"); + jsonWriter.value(1); + jsonWriter.endObject(); + assertEquals("{\"a\":{\"b\":true},\"c\":1}", stringWriter.toString()); + } + public void testNonFiniteDoubles() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); -- cgit v1.2.3