Skip to content

Commit

Permalink
JsonWriter#jsonValue writes raw JSON values.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Adam Tanner committed Jul 20, 2015
1 parent bb34247 commit f7abd59
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
17 changes: 17 additions & 0 deletions gson/src/main/java/com/google/gson/stream/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,23 @@ public JsonWriter value(String value) throws IOException {
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}.
*
Expand Down
12 changes: 12 additions & 0 deletions gson/src/test/java/com/google/gson/stream/JsonWriterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,18 @@ public void testNullStringValue() throws IOException {
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);
Expand Down

0 comments on commit f7abd59

Please sign in to comment.