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 .