我有java类,其中包含简单的String
字段,其中一些字段可以包含非ascii符号,并且在JSON序列化期间,这些符号将在\u0000
中转换。我知道杰克逊可以做到这一点,但内部原因无法使用它。
如前。 Java类
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:'Пример'}
答案 0 :(得分:2)
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 );