skip to Main Content

I have a String like this:

private String jsonString = "{\"test\":\"value \\\"ciao\\\"  \"}"

At runtime this should be: {"test":"value \"ciao\" "}

Now I want to remove the only the first level of escape and leaving the nested escape.

The result should be:
{"test":"value "ciao" "}

How can I do this? Is it possible with methods like replace() or replaceAll()?

2

Answers


  1. You can use replaceAll() like this:

    public class Main {
        public static void main(String[] args) {
            String jsonString = "{\"test\":\"value \\\"ciao\\\"  \"}";
    
            String unescapedString = jsonString.replaceAll("\\\\", "\\").replaceAll("\\\"", """);
    
            System.out.println(unescapedString);
        }
    }
    
    Login or Signup to reply.
  2. You can use the String#translateEscapes method.

    String s = "{\"test\":\"value \\\"ciao\\\"  \"}";
    s = s.translateEscapes();
    

    Output

    {"test":"value "ciao"  "}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search