JsonCharEscaper implements Function<Integer, String> { @Nullable @Override public String apply(final Integer i) { if (0 <= i && i < ESCAPE_TABLE.length) { return ESCAPE_TABLE[i]; } else { return null; } } private  JsonCharEscaper(); static JsonCharEscaper getInstance(); @Nullable @Override String apply(final Integer i);  }
@Test public void doNotEscapeNormalCharactersBeforeBackslash() { final int start = 0x0020; final int end = 0x00FFFF; IntStream.range(start, end) .filter(i -> i != '"' && i != '\\') .forEach(character -> { final String notEscaped = underTest.apply(character); assertThat(notEscaped) .isNull(); }); }
@Test public void escapeQuote() { final String escapedQuote = underTest.apply((int) '"'); assertThat(escapedQuote).isEqualTo("\\\""); }
@Test public void escapeReverseSolidus() { final String escapedReverseSolidus = underTest.apply((int) '\\'); assertThat(escapedReverseSolidus).isEqualTo("\\\\"); }
@Test public void escapeControlCharactersWithoutShorthands() { IntStream.range(0, 0x1F).forEach(character -> { if (SHORTHAND_CONTROL_CHARACTERS.chars().noneMatch(i -> i == character)) { final String unicodeEscaped = underTest.apply(character); assertThat(unicodeEscaped) .describedAs("Do not escape character %s", Integer.toHexString(character)) .startsWith("\\u"); assertThat(Integer.parseInt(unicodeEscaped.substring(2), 16)).isEqualTo(character); } }); }
@Test public void escapeControlCharactersWithShorthands() { SHORTHAND_CONTROL_CHARACTERS.chars().forEach(character -> { final String escaped = underTest.apply(character); final String expected = "\\" + SHORTHAND_CONTROL_CHARACTER_NAMES.charAt(SHORTHAND_CONTROL_CHARACTERS.indexOf(character)); assertThat(escaped).isEqualTo(expected); }); }