8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マルチバイト文字と指定の文字をエスケープしたJSONを作る(Jacksonを使用)

Posted at

サロゲートペアの文字でもちゃんとエスケープしてくれる。

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"}'
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?