Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson cannot parse control character

Tags:

java

json

jackson

In my API response, I have control-p character. Jackson parser fails to serialize the character and throws an error

com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 16)): has to be escaped using backslash to be included in string value

I have investigated and found that Jackson library actually tries to catch for ctrl-char.

Can anyone suggest solutions or work around for this? Thanks in advance.

like image 439
June Woo Suk Avatar asked Sep 15 '15 19:09

June Woo Suk


People also ask

What went wrong with JSON parse ()?

What went wrong? JSON.parse () parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered. Both lines will throw a SyntaxError: Omit the trailing commas to parse the JSON correctly: You cannot use single-quotes around properties, like 'foo'.

What is the error when serializing a character in Jackson?

Jackson parser fails to serialize the character and throws an error com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ( (CTRL-CHAR, code 16)): has to be escaped using backslash to be included in string value

How are control characters encoded in the JSON output?

Control characters. If the source data contains control characters, the FOR JSON clause encodes them in the JSON output in u<code> format, as shown in the following table.

How for JSON escapes special characters and control characters (SQL Server)?

How FOR JSON escapes special characters and control characters (SQL Server) 1 Escaping of special characters. If the source data contains special characters, the FOR JSON clause escapes them in the JSON output with \, as shown in the following table. 2 Control characters. ... 3 Learn more about JSON in SQL Server and Azure SQL Database


2 Answers

I was able to fix similar problem by setting Feature.ALLOW_UNQUOTED_CONTROL_CHARS (documentation) on JsonParser .

The code in my case looks:

parser.setFeatureMask(parser.getFeatureMask() | JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS.getMask());

As stated by others, such JSON is invalid, but in case you have no chance to change JSON, this should help.

like image 151
JanSedlacek Avatar answered Nov 20 '22 17:11

JanSedlacek


Have you tried to configure the mapper to force escape non-ASCII?

This might be enough:

mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);

see documentation

But I agree with StaxMan: the JSON response should be well formatted.

like image 34
Martijn Bruckman Avatar answered Nov 20 '22 16:11

Martijn Bruckman