サロゲートペアの文字でもちゃんとエスケープしてくれる。
import org.codehaus.jackson.map.ObjectMapper
import org.codehaus.jackson.io.CharacterEscapes
import org.codehaus.jackson.SerializableString
import org.codehaus.jackson.JsonGenerator.Feature
@Grab('org.codehaus.jackson:jackson-mapper-lgpl:1.9.9')
public class CustomCharacterEscapes extends CharacterEscapes {
private final int[] _asciiEscapes;
public CustomCharacterEscapes() {
_asciiEscapes = standardAsciiEscapesForJSON();
_asciiEscapes['/'] = CharacterEscapes.ESCAPE_STANDARD;
_asciiEscapes['<'] = CharacterEscapes.ESCAPE_STANDARD;
_asciiEscapes['>'] = CharacterEscapes.ESCAPE_STANDARD;
_asciiEscapes['+'] = CharacterEscapes.ESCAPE_STANDARD;
}
@Override
public int[] getEscapeCodesForAscii() {
return _asciiEscapes;
}
@Override
public SerializableString getEscapeSequence(int i) {
return null;
}
}
def mapper = new ObjectMapper()
mapper.configure(Feature.ESCAPE_NON_ASCII, true)
mapper.getJsonFactory().setCharacterEscapes(new CustomCharacterEscapes())
def map = ["名前":"長谷川一清","code":"<script>alert(1)</script>"]
def json = mapper.writeValueAsString(map)
assert json == '{"\\u540D\\u524D":"\\u9577\\u8C37\\u5DDD\\u4E00\\u6E05","code":"\\u003Cscript\\u003Ealert(1)\\u003C\\u002Fscript\\u003E"}'