81 lines
2.7 KiB
Java
81 lines
2.7 KiB
Java
package com.google.gson.util;
|
|
|
|
/**
|
|
* Utilities methods for escaping strings, extracted from gsons JsonWriter.
|
|
* @author JFronny
|
|
*/
|
|
public class StringEscapeUtil {
|
|
private StringEscapeUtil() {}
|
|
|
|
/*
|
|
* From RFC 8259, "All Unicode characters may be placed within the
|
|
* quotation marks except for the characters that must be escaped:
|
|
* quotation mark, reverse solidus, and the control characters
|
|
* (U+0000 through U+001F)."
|
|
*
|
|
* We also escape '\u2028' and '\u2029', which JavaScript interprets as
|
|
* newline characters. This prevents eval() from failing with a syntax
|
|
* error. http://code.google.com/p/google-gson/issues/detail?id=341
|
|
*/
|
|
private static final String[] REPLACEMENT_CHARS;
|
|
private static final String[] HTML_SAFE_REPLACEMENT_CHARS;
|
|
|
|
static {
|
|
REPLACEMENT_CHARS = new String[128];
|
|
for (int i = 0; i <= 0x1f; i++) {
|
|
REPLACEMENT_CHARS[i] = String.format("\\u%04x", i);
|
|
}
|
|
REPLACEMENT_CHARS['"'] = "\\\"";
|
|
REPLACEMENT_CHARS['\\'] = "\\\\";
|
|
REPLACEMENT_CHARS['\t'] = "\\t";
|
|
REPLACEMENT_CHARS['\b'] = "\\b";
|
|
REPLACEMENT_CHARS['\n'] = "\\n";
|
|
REPLACEMENT_CHARS['\r'] = "\\r";
|
|
REPLACEMENT_CHARS['\f'] = "\\f";
|
|
REPLACEMENT_CHARS['\0'] = "\\0";
|
|
HTML_SAFE_REPLACEMENT_CHARS = REPLACEMENT_CHARS.clone();
|
|
HTML_SAFE_REPLACEMENT_CHARS['<'] = "\\u003c";
|
|
HTML_SAFE_REPLACEMENT_CHARS['>'] = "\\u003e";
|
|
HTML_SAFE_REPLACEMENT_CHARS['&'] = "\\u0026";
|
|
HTML_SAFE_REPLACEMENT_CHARS['='] = "\\u003d";
|
|
HTML_SAFE_REPLACEMENT_CHARS['\''] = "\\u0027";
|
|
}
|
|
|
|
private static String getReplacement(char c, String[] replacements) {
|
|
String replacement;
|
|
if (c < 128) {
|
|
replacement = replacements[c];
|
|
if (replacement == null) {
|
|
return null;
|
|
}
|
|
} else if (c == '\u2028') {
|
|
replacement = "\\u2028";
|
|
} else if (c == '\u2029') {
|
|
replacement = "\\u2029";
|
|
} else {
|
|
return null;
|
|
}
|
|
return replacement;
|
|
}
|
|
|
|
/**
|
|
* Returns the replacement for the character, or null if the character does not need to be escaped.
|
|
* @param c the character to escape
|
|
* @return the replacement for the character, or null if the character does not need to be escaped
|
|
* @see #getHtmlSafeReplacement(char)
|
|
*/
|
|
public static String getReplacement(char c) {
|
|
return getReplacement(c, REPLACEMENT_CHARS);
|
|
}
|
|
|
|
/**
|
|
* Returns the replacement for the character, or null if the character does not need to be escaped.
|
|
* @param c the character to escape
|
|
* @return the replacement for the character, or null if the character does not need to be escaped
|
|
* @see #getReplacement(char)
|
|
*/
|
|
public static String getHtmlSafeReplacement(char c) {
|
|
return getReplacement(c, HTML_SAFE_REPLACEMENT_CHARS);
|
|
}
|
|
}
|