Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted within </, producing <\/, allowing JSON text to be delivered in HTML. In JSON text, a string cannot contain a control character or an unescaped quote or backslash. @param string A String
(String string)
| 1147 | * @return A String correctly formatted for insertion in a JSON text. |
| 1148 | */ |
| 1149 | public static String quote(String string) { |
| 1150 | if (string == null || string.length() == 0) { |
| 1151 | return "\"\""; |
| 1152 | } |
| 1153 | |
| 1154 | char b; |
| 1155 | char c = 0; |
| 1156 | String hhhh; |
| 1157 | int i; |
| 1158 | int len = string.length(); |
| 1159 | StringBuffer sb = new StringBuffer(len + 4); |
| 1160 | |
| 1161 | sb.append('"'); |
| 1162 | for (i = 0; i < len; i += 1) { |
| 1163 | b = c; |
| 1164 | c = string.charAt(i); |
| 1165 | switch (c) { |
| 1166 | case '\\': |
| 1167 | case '"': |
| 1168 | sb.append('\\'); |
| 1169 | sb.append(c); |
| 1170 | break; |
| 1171 | case '/': |
| 1172 | if (b == '<') { |
| 1173 | sb.append('\\'); |
| 1174 | } |
| 1175 | sb.append(c); |
| 1176 | break; |
| 1177 | case '\b': |
| 1178 | sb.append("\\b"); |
| 1179 | break; |
| 1180 | case '\t': |
| 1181 | sb.append("\\t"); |
| 1182 | break; |
| 1183 | case '\n': |
| 1184 | sb.append("\\n"); |
| 1185 | break; |
| 1186 | case '\f': |
| 1187 | sb.append("\\f"); |
| 1188 | break; |
| 1189 | case '\r': |
| 1190 | sb.append("\\r"); |
| 1191 | break; |
| 1192 | default: |
| 1193 | if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || |
| 1194 | (c >= '\u2000' && c < '\u2100')) { |
| 1195 | hhhh = "000" + Integer.toHexString(c); |
| 1196 | sb.append("\\u" + hhhh.substring(hhhh.length() - 4)); |
| 1197 | } else { |
| 1198 | sb.append(c); |
| 1199 | } |
| 1200 | } |
| 1201 | } |
| 1202 | sb.append('"'); |
| 1203 | return sb.toString(); |
| 1204 | } |
| 1205 | |
| 1206 | /** |
no test coverage detected