JavaStringToEscapedJsonString implements UnaryOperator<String> { @Override public String apply(final String javaString) { requireNonNull(javaString, "The Java String to be converted must not be null"); final StringBuilder stringBuilder = new StringBuilder(javaString.length() + 2); stringBuilder.append(QUOTE); stringBuilder.append(javaString); int i = 1; for (final char c : javaString.toCharArray()) { @Nullable final String replacement = jsonCharEscaper.apply((int) c); if (null != replacement) { stringBuilder.replace(i, i + 1, replacement); i += replacement.length(); } else { i++; } } stringBuilder.append(QUOTE); return stringBuilder.toString(); } private  JavaStringToEscapedJsonString(final Function<Integer, String> theJsonCharEscaper); static JavaStringToEscapedJsonString getInstance(); @Override String apply(final String javaString);  }
@Test public void convertJavaStringWithoutSpecialChars() { final String javaString = "Auf der Wiese blueht ein kleines Bluemelein."; final String expected = "\"" + javaString + "\""; final String actual = underTest.apply(javaString); assertThat(actual).isEqualTo(expected); }
@Test public void convertJavaStringWithSpecialChars() { final String javaString = "Auf der Wiese\n blueht ein kleines \"Blümelein\"."; final String expected = "\"" + "Auf der Wiese\\n blueht ein kleines \\\"Blümelein\\\"." + "\""; final String actual = underTest.apply(javaString); assertThat(actual).isEqualTo(expected); }