Cedric
Cedric

Reputation: 95

jackson parser backslash double quote not work

I met a problem when I try to convert json to map.

I use jakson, and here is my mapper():

        mapper = new ObjectMapper();
        mapper.setTimeZone(TimeFormat.getDefaultTimeZone());
        mapper.configure(com.fasterxml.jackson.databind.MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, false);
        mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
        mapper.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        format.setTimeZone(TimeFormat.getDefaultTimeZone());
        mapper.setDateFormat(format);

Here is the 'bad' json:

{..."id":660273193,"orderId":220575205,"orderItemAmount":5.6,"orderItemNum":2,"orderItemPrice":2.8,"productCName":"16\\" Shoes","productId":23373137,...

Error Info is:Unexpected character ('S' (code 22609 / 0x5851)): was expecting comma to separate OBJECT entries The user set 16" 10 as the productName, but failed converting it from json to map. I tried Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER but not work. Are there any configurations that I haven't found for this kind of situation?

Upvotes: 1

Views: 8906

Answers (1)

Alexey Gavrilov
Alexey Gavrilov

Reputation: 10853

It looks like you should use one backslash to escape a quote if you are reading from an external source, or three backslashes if you are reading a JSON string from a Java constant. Here is an example:

public class JacksonBackslash {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
       // mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        String json = "{\"productCName\":\"16\\\" Shoes\"}";
        System.out.println(json);
        System.out.println(mapper.readValue(json, new TypeReference<Map<String, Object>>() {}));
    }
}

Output:

{"productCName":"16\" Shoes"}
{productCName=16" Shoes}

Upvotes: 2

Related Questions