jackson序列化字符串反斜杠时会把转义符也序列化出来。就是个数不对,如何解?
使用jackson json序列化java对象,当String类型的属性值包含反斜杠时,序列化结果不正确,包含转义字符。如:
String str = "\\";
list.add(str);
sysout(list); // 输出结果是这个反斜杠 ["\"]
// 使用jackson序列化
String json = objectMapper.writeValueAsString(list);
sysout(json); // 输出结果有两个反斜杠["\\"]
我想问,jackson本身有没有解决办法?还是我的姿势不对,大家没有遇到这种问题?
手机打的不太方便,大家将就下。
谢谢!
缭乱的祈祷
10 years, 1 month ago
Answers
Jackson 1.8有"character escapes"的功能,你可以使用该功能定义转义规则。
简单来说,你需要实现CharacterEscapes
请参考 http://jackson.codehaus.org/1.8.2/jav...
示例代码如下:
public class CustomCharacterEscapes extends CharacterEscapes {
private final int[] _asciiEscapes;
public CustomCharacterEscapes() {
_asciiEscapes = standardAsciiEscapesForJSON();
_asciiEscapes['/'] = CharacterEscapes.ESCAPE_CUSTOM;
}
@Override
public int[] getEscapeCodesForAscii() {
return _asciiEscapes;
}
@Override
public SerializableString getEscapeSequence(int i) {
if(i == '/'){
return new SerializableString() {
@Override
public String getValue() {
return "\\/";
}
@Override
public int charLength() {
return 2;
}
@Override
public char[] asQuotedChars() {
return new char[]{'\\','/'};
}
@Override
public byte[] asUnquotedUTF8() {
return new byte[]{'\\','/'};
}
@Override
public byte[] asQuotedUTF8() {
return new byte[]{'\\','/'};
}
};
}
else{
return null;
}
}
}
纳爱斯勃特
answered 9 years, 5 months ago