JsonEscaper { public static void jsonEscape(CharSequence in, WriteBuffer out) { int length = in.length(); if (length == 0) return; int afterReplacement = 0; for (int i = 0; i < length; i++) { char c = in.charAt(i); String replacement; if (c < 0x80) { replacement = REPLACEMENT_CHARS[c]; if (replacement == null) continue; } else if (c == '\u2028') { replacement = U2028; } else if (c == '\u2029') { replacement = U2029; } else { continue; } if (afterReplacement < i) { out.writeUtf8(in, afterReplacement, i); } out.writeUtf8(replacement, 0, replacement.length()); afterReplacement = i + 1; } if (afterReplacement < length) { out.writeUtf8(in, afterReplacement, length); } }  static int jsonEscapedSizeInBytes(CharSequence v); static void jsonEscape(CharSequence in, WriteBuffer out);  }
@Test public void testJsonEscape() { WriteBuffer buffer = new WriteBuffer(buf, 0); jsonEscape(new String(new char[] {0, 'a', 1}), buffer); assertThat(buffer).hasToString("\\u0000a\\u0001"); buffer.pos = 0; jsonEscape(new String(new char[] {'"', '\\', '\t', '\b'}), buffer); assertThat(buffer).hasToString("\\\"\\\\\\t\\b"); buffer.pos = 0; jsonEscape(new String(new char[] {'\n', '\r', '\f'}), buffer); assertThat(buffer).hasToString("\\n\\r\\f"); buffer.pos = 0; jsonEscape("\u2028 and \u2029", buffer); assertThat(buffer).hasToString("\\u2028 and \\u2029"); buffer.pos = 0; jsonEscape("\"foo", buffer); assertThat(buffer).hasToString("\\\"foo"); }