-2

I am not able to get the message value in the desired format.

String url = "sample"
String message ="/test{\"url\":"' + url + '\"}

The desired value of message is "/test{\"url\":\"sample\"}"

Any idea on this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aditya
  • 950
  • 8
  • 37
  • 1
    you just copy the expected string then paste into ide, ide(in my case, intellij idea) will escape quotes for you. – Lei Yang Feb 08 '22 at 13:54
  • @LeiYang, I want the url value to be picked up dynamically from the url variable – Aditya Feb 08 '22 at 13:58
  • You need to escape slashes like this String message = "/test{\\\"url\\\":\\\"sample\\\"}"; You have another answer here https://stackoverflow.com/a/23363356/6584664 – Youri C. Feb 08 '22 at 14:12

3 Answers3

2

Try with this:

    String url = "sample";
    String message ="/test{\\\"url\\\":\""+url+"\\\"}";

Or you can use String.format:

    String url = "sample";
    String message = String.format("/test{\\\"url\\\":\"%s\\\"}",url);
fabio19933
  • 124
  • 8
1

Try the following syntax:

String url = "sample";
String message ="/test{\\\"url\\\":\"" + url + "\\\"}";

Please note that back-slash \ and double-quote " are specialized character and hence they need to be escaped using back-slash \. Hence, \\ is used for \ and \" is used for " in String literal.

Output:

/test{\"url\":"sample\"}
Keyur Panchal
  • 1,382
  • 1
  • 10
  • 15
1

After several tried, I found the solution:

    StringBuilder sb=new StringBuilder();
    sb.append("\"/test{");
    sb.append("\"\\");
    sb.append("\"");
    sb.append("url\\\"");
    sb.append(":");
    sb.append("\\\"");
    sb.append(url);
    sb.append("\"\\}\"");
    System.out.println(sb.toString());
The KNVB
  • 3,588
  • 3
  • 29
  • 54