如何使用Java解析带有UTF-8字符的json字符串?

时间:2019-04-08 15:14:01

标签: java json jackson jsonparser

我有一个带SUBSTITUTE()utf-8字符的json字符串。当我尝试使用杰克逊将json字符串转换为java对象时,出现解析异常。您能否让我知道如何编码和解码utf-8字符?

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonString, MY_DOMAIN_OBJECT.class);

jsonString:

{"studentId":"753253-2274", "information":[{"key":"1","value":"Get alerts on your phone(SUBSTITUTE character is present here. Unable to paste it)To subscribe"}]}

enter image description here

错误:

Illegal unquoted character ((CTRL-CHAR, code 26)): has to be escaped using backslash to be included in string value

1 个答案:

答案 0 :(得分:3)

你可以试试吗?

ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
mapper.readValue(jsonString, MY_DOMAIN_OBJECT.class);

我希望它可以帮助您: Javadoc

  

确定解析器是否允许JSON字符串包含未加引号的控制字符(值小于32的ASCII字符,包括制表符和换行符)的功能。如果feature设置为false,则遇到此类字符将引发异常。   由于JSON规范要求所有控制字符都加引号,因此这是一项非标准功能,因此默认情况下处于禁用状态。