jackson把json字符串转对象出错
2019-03-05 本文已影响0人
风一样的存在
最近遇到一个奇葩的问题,json字符串中含有unicode编码,但是却无法转码。即使转码之后也是一些类似于(á��á��á��á�¸ á�¢á�¶á��á�¼)这样的字符。
{
"education_experiences": [
{
"name": "\u00e6\u00b9\u0096\u00e5\u008c\u0097\u00e6\u0096\u0087\u00e7\u0090\u0086\u00e5\u00ad\u00a6\u00e9\u0099\u00a2",
"start_timestamp": 1346428800,
"end_timestamp": 1464753600,
"graduated": true,
"concentrations": [
"\u00e8\u00ae\u00a1\u00e7\u00ae\u0097\u00e6\u009c\u00ba\u00e7\u00a7\u0091\u00e5\u00ad\u00a6\u00e4\u00b8\u0093\u00e4\u00b8\u009a",
"\u00e9\u009f\u00b3\u00e4\u00b9\u0090\u00e5\u00ad\u00a6"
],
"school_type": "College"
},
{
"name": "\u00e8\u00a5\u0084\u00e5\u00b7\u009e\u00e5\u008c\u00ba\u00e4\u00ba\u008c\u00e4\u00b8\u00ad",
"start_timestamp": 1220716800,
"end_timestamp": 1307678400,
"graduated": true,
"description": "high",
"school_type": "High School"
}
]
}
最后问了同事采用下面的代码解决了这个问题:
String content = FileUtils.readFileToString(new File(filePath),"utf-8");
content = StringEscapeUtils.unescapeJava(content);
ObjectMapper mapper=new ObjectMapper();
content = new String(content.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
但是如果字符串中含有换行符就会出错:
Caused by: com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
增加配置解决:
mapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
参考文档: