public static String sanitize(String value, boolean clean, Character... toEscape) {

        StringBuilder builder = new StringBuilder();
        Map<Character, String> replacements = clean ? CLEAN_CHARS : REPLACEMENT_CHARS;

        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);

            if (toEscape == null) {
                if (replacements.containsKey(c)) {
                    builder.append(replacements.get(c));
                } else {
                    builder.append(c);
                }
            } else {
                if (replacements.containsKey(c) && contains(toEscape, c)) {
                    builder.append(replacements.get(c));
                } else {
                    builder.append(c);
                }
            }
        }
        return builder.toString();
    }
public static String sanitize ( String value , boolean clean , Character ... toEscape ) { StringBuilder builder = new StringBuilder ( ) ; Map < Character , String > replacements = clean ? CLEAN_CHARS : REPLACEMENT_CHARS ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char c = value . charAt ( i ) ; if ( toEscape == null ) { if ( replacements . containsKey ( c ) ) { builder . append ( replacements . get ( c ) ) ; } else { builder . append ( c ) ; } } else { if ( replacements . containsKey ( c ) && contains ( toEscape , c ) ) { builder . append ( replacements . get ( c ) ) ; } else { builder . append ( c ) ; } } } return builder . toString ( ) ; }
Escapes control characters in a string when you need to
generate JSON.

@param value    input string
@param clean    if true will remove characters that match, if false will escape
@param toEscape array of characters to escape. If not provided, it will escape or clean <code>'"','\\', '\t', '\b', '\n', '\r' '\f'</code>.
This method will only escape or clean if provided chars are from this list.
@return input string with control characters escaped or removed, depending on the <code>clean</code> flag.