improve JSON escape, closes #6
This commit is contained in:
parent
d4e06c58ed
commit
dc303bd322
1 changed files with 35 additions and 12 deletions
|
@ -45,8 +45,6 @@ import java.util.concurrent.locks.Lock;
|
|||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
|
@ -65,14 +63,6 @@ public class MarcJsonWriter extends MarcContentHandler implements Flushable, Clo
|
|||
|
||||
private static final int DEFAULT_BUFFER_SIZE = 65536;
|
||||
|
||||
private static final Pattern quotePattern = Pattern.compile("\"", Pattern.LITERAL);
|
||||
|
||||
private static final Pattern backslashPattern = Pattern.compile("\\\\");
|
||||
|
||||
private static final String ESCAPE_QUOTE = "\\\"";
|
||||
|
||||
private static final String ESCAPE_BACKSLASH = "\\\\";
|
||||
|
||||
private final Lock lock;
|
||||
|
||||
private final StringBuilder sb;
|
||||
|
@ -155,8 +145,41 @@ public class MarcJsonWriter extends MarcContentHandler implements Flushable, Clo
|
|||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
String s = backslashPattern.matcher(value).replaceAll(Matcher.quoteReplacement(ESCAPE_BACKSLASH));
|
||||
return quotePattern.matcher(s).replaceAll(Matcher.quoteReplacement(ESCAPE_QUOTE));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
switch (c) {
|
||||
case '"':
|
||||
sb.append("\\\"");
|
||||
break;
|
||||
case '\\':
|
||||
sb.append("\\\\");
|
||||
break;
|
||||
case '\b':
|
||||
sb.append("\\b");
|
||||
break;
|
||||
case '\f':
|
||||
sb.append("\\f");
|
||||
break;
|
||||
case '\n':
|
||||
sb.append("\\n");
|
||||
break;
|
||||
case '\r':
|
||||
sb.append("\\r");
|
||||
break;
|
||||
case '\t':
|
||||
sb.append("\\t");
|
||||
break;
|
||||
default:
|
||||
if (c < 0x1f) {
|
||||
sb.append("\\u").append(String.format("%04x", (int) c));
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public MarcJsonWriter setIndex(String index, String indexType) {
|
||||
|
|
Loading…
Reference in a new issue