Jackson: customization escaping of double quotes while serialize an object to json

16,043

This will produce invalid JSON, so Jackson isn't going to help you do that. Assuming that you have no reverse solidus in the member names, you can just do it after outputting the actual string value:

String invalid = mapper.writeValueAsString(object).replace("\\", "\\\\");
Share:
16,043
kali
Author by

kali

Updated on June 05, 2022

Comments

  • kali
    kali almost 2 years

    By default jackson escape double quotes by backslash: \". So the json object looks like

    {"title": "Testing \"double quotes\""}
    

    I want to escape double quotes by two backslashes: \\". Like this

    {"title": "Testing \\"double quotes\\""}
    

    How to customize jackson serialization strategy for double quotes?

  • kali
    kali over 9 years
    So, isn't there any way to configure jackson to produce json like I want?
  • Aaryn Tonita
    Aaryn Tonita over 9 years
    I don't think you will be able to. As I said, the JSON you want to produce is invalid. The quotation mark inside of the string is not escaped since you have escaped the '\' instead, so the next character in valid json should be '}', ']', or ',' but you will have 'd'. Why do you want the double '\' anyways?
  • kali
    kali over 9 years
    Thank you for your answers, Aaryn. I was trying to make double '\' because of a template engine I use. There is a custom writer escapes all '"' while it renders a model to a template. So, '\"' becomes '\\"' which is incorrect. I fix my problem by customization of the writer.