From d3a4b48ad92ce5e5a45a7046e737984608c22cc6 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Tue, 12 Jul 2011 16:05:22 +0000 Subject: [PATCH] Unconditionally escape unicode newline characters. Fixes issue 341. --- .../src/main/java/com/google/gson/stream/JsonWriter.java | 9 +++++++++ .../test/java/com/google/gson/stream/JsonWriterTest.java | 9 +++++++++ 2 files changed, 18 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 dba653a1..0e3691ce 100644 --- a/gson/src/main/java/com/google/gson/stream/JsonWriter.java +++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java @@ -431,6 +431,10 @@ public final class JsonWriter implements Closeable { * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." + * + * We also escape '\u2028' and '\u2029', which JavaScript interprets as + * newline characters. This prevents eval() from failing with a syntax + * error. http://code.google.com/p/google-gson/issues/detail?id=341 */ switch (c) { case '"': @@ -471,6 +475,11 @@ public final class JsonWriter implements Closeable { } break; + case '\u2028': + case '\u2029': + out.write(String.format("\\u%04x", (int) c)); + break; + default: if (c <= 0x1F) { out.write(String.format("\\u%04x", (int) c)); 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 3b60b184..41a9621c 100644 --- a/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java +++ b/gson/src/test/java/com/google/gson/stream/JsonWriterTest.java @@ -290,6 +290,15 @@ public final class JsonWriterTest extends TestCase { + "\"\\u0019\"]", stringWriter.toString()); } + public void testUnicodeLineBreaksEscaped() throws IOException { + StringWriter stringWriter = new StringWriter(); + JsonWriter jsonWriter = new JsonWriter(stringWriter); + jsonWriter.beginArray(); + jsonWriter.value("\u2028 \u2029"); + jsonWriter.endArray(); + assertEquals("[\"\\u2028 \\u2029\"]", stringWriter.toString()); + } + public void testEmptyArray() throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter);