通过 Flex 转义非 ASCII 符号 JSON

Escape non-ascii symbols by Flex JSON

我有 java class,它包含简单的 String 字段,其中一些字段可以包含非 ascii 符号,并且在 JSON 序列化期间,这个符号将在 \u0000 内转换。我知道Jackson可以做到,但是内部原因不能用

如前。 Javaclass

public class SomeClass {
    String filed1;

    // getter/setter
}

转换后的代码:

public String convert(SomeClass someClass) {
    new JSONSerializer().include( "*" ).serialize(someClass);
}

结果应该是 JSON:

{fild1:'\u041F\u0440\u0438\u0432\u0435\u0442'}

而不是

{fild1:'Пример'}

好的,我已经找到解决办法了。可能对某人有帮助。

JSONSerializer serializer = new JSONSerializer().transform( new AbstractTransformer() {
        @Override
        public void transform(Object object) {

            String value = object.toString();
            int len = value.length();
            StringBuilder stringBuilder = new StringBuilder("\"");
            for (int i = 0; i < len; i++) {
                char c = value.charAt( i );
                if (c == '"') {
                    stringBuilder.append( "\u0022" );
                } else if (c == '&') {
                    stringBuilder.append( "\u0026" );
                } else if (c == '\'') {
                    stringBuilder.append( "\u0027" );
                } else if (c == '\') {
                    stringBuilder.append( "\\" );
                } else if (c == '\b') {
                    stringBuilder.append( "\b" );
                } else if (c == '\f') {
                    stringBuilder.append( "\f" );
                } else if (c == '\n') {
                    stringBuilder.append( "\n" );
                } else if (c == '\r') {
                    stringBuilder.append( "\r" );
                } else if (c == '\t') {
                    stringBuilder.append( "\t" );
                } else if (c > 127) {
                    stringBuilder.append( "\u" );
                    int n = c;
                    for (int j = 0; j < 4; ++j) {
                        int digit = (n & 0xf000) >> 12;
                        stringBuilder.append( String.valueOf( JSONSerializer.HEX[digit] ) );
                        n <<= 4;
                    }
                } else {
                    stringBuilder.append( c );
                }
            }
            stringBuilder.append( "\"" );
            getContext().write( stringBuilder.toString() );
        }
    }, String.class );