1. 程式人生 > 其它 >jackson反序列化 過濾特殊字元 控制字元

jackson反序列化 過濾特殊字元 控制字元

jacskon預設是可以序列化一些特殊字元

但反序列化時就不支援了

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 31)): has to be escaped using backslash to be included in string value
 at [Source: (String)"{
  "mpExist": 1,
  "shortName": "xflbx38",
  "typeChain": "|0|91|94|"
}
"; line: 3, column: 25]
	at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1840)
	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:712)
	at com.fasterxml.jackson.core.base.ParserBase._throwUnquotedSpace(ParserBase.java:1046)
	at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._finishString2(ReaderBasedJsonParser.java:2068)
	at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._finishString(ReaderBasedJsonParser.java:2039)
	at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.getText(ReaderBasedJsonParser.java:294)
	at com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer$Vanilla.deserialize(UntypedObjectDeserializer.java:672)
	at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:527)
	at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:364)
	at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3205)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3173)

解決方法

1、反序化時,開啟配置

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);

成功反序列化

2、但是很多情況,比如上游發你的資料,這些特殊字元沒有意義。你需要過濾它怎麼辦?

檢視jackson的API文件

好,我們替換這些字元

static final int INT_SPACE = 0x0020;

/**
  * 丟棄值小於32的ASCII字元,包括製表符和換行符等 <br>
 * 參考ASCII的值 http://www.asciima.com/
 */
public static String cleanJsonControlChar(String inputStr) {
    if (StringUtils.isEmpty(inputStr)) {
            return inputStr;
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < inputStr.length(); i++) {
        char c = inputStr.charAt(i);
         if (c < INT_SPACE) {
             sb.append(" ");
             continue;
         }
         sb.append(c);
    }
    return sb.toString();
}