Created
September 1, 2012 04:30
-
-
Save kanemu/3563851 to your computer and use it in GitHub Desktop.
[groovy][java][jackson]マルチバイト文字と指定の文字をエスケープしたjsonを作る。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.codehaus.jackson.map.ObjectMapper | |
import org.codehaus.jackson.io.CharacterEscapes | |
import org.codehaus.jackson.SerializableString | |
import org.codehaus.jackson.JsonGenerator.Feature | |
@Grab(group='org.codehaus.jackson', module='jackson-mapper-lgpl', version='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"}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment