Skip to content

Instantly share code, notes, and snippets.

@jrmuizel
Created May 3, 2025 01:31
Show Gist options
  • Save jrmuizel/2e0e6d941b7e00ae6e068611d4ff9814 to your computer and use it in GitHub Desktop.
Save jrmuizel/2e0e6d941b7e00ae6e068611d4ff9814 to your computer and use it in GitHub Desktop.
Stream string values
class StringWriter extends Writer {
public StringWriter(Writer out) {
this.out = out;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
char c = cbuf[i + off];
/*
* From RFC 4627, "All Unicode characters may be placed within the
* 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 '"':
case '\\':
out.write('\\');
out.write(c);
break;
case '\t':
out.write("\\t");
break;
case '\b':
out.write("\\b");
break;
case '\n':
out.write("\\n");
break;
case '\r':
out.write("\\r");
break;
case '\f':
out.write("\\f");
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));
} else {
out.write(c);
}
break;
}
}
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.write("\"");
}
Writer out;
}
public StringWriter writeString() throws IOException {
beforeValue(false);
out.write("\"");
StringWriter stringWriter = new StringWriter(out);
return stringWriter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment