JSON ESCAPE using Control-Characters

28 views Asked by At

I have following code to escape control character but somehow I have two \\ before unicode in the output as shown below

"merLoc": "G.ELL                   **\\**u0003\\u009c\\u0009ME         AU",

Code:

public void initMapper() {
    objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
    objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);

    // objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
    // objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    
    objectMapper.registerModule(new JavaTimeModule());
    objectMapper.setDateFormat(new RFC3339DateFormat());         
}

public static void escapeControlCharacters(Map<String, Object> map) {
    for (Map.Entry<String, Object> entry : map.entrySet()) {
        Object value = entry.getValue();
        if (value instanceof String) {
            String escapeValue = escapeControlCharactersInString((String) value);
            entry.setValue(escapeValue);
        }
    }
}

public static String escapeControlCharactersInString(String input) {
    StringBuilder escaped = new StringBuilder(input.length());
    for(char c : input.toCharArray()) {
        if (Character.isISOControl(c)) {
            escaped.append(String.format("\\u%04x", (int)c));
        } else {
            escaped.append(c);
        }
    }
    return escaped.toString();
}
0

There are 0 answers