1

I have a string with escape characters in such a way that the when the string is printed it results in another string with valid escape characters. How do i retrieve that string which looks like the one when the first string is printed?

Here's the code - the initial string looks as such:

String string = "{\"agent\":\"{\\\"name\\\":\\\"James Bond\\\"}\"}";
System.out.println("str: "+string);

Executing the code would produce

str: {"agent":"{\"name\":\"James Bond\"}"}

I was to get the string as it appears in the output.

Chai Nadig
  • 417
  • 1
  • 6
  • 23
  • 1
    How *does* this String appear in the output? Why `\\\"name\\\"` instead of `\"name\"`? –  Oct 30 '12 at 12:08
  • well i guess u can simply replace all " and \ with \" and \\. To do so use string.replace – gabrjan Oct 30 '12 at 12:10
  • How would you like the String to be printed? Can you give an example? – Gijs Overvliet Oct 30 '12 at 12:10
  • 3
    Why are you attempting to write/parse json manually? There are a ton of libraries for that. – tier1 Oct 30 '12 at 12:11
  • The second block of code shows how the string appears in the output. I was working with JSONs when I came across this problem. – Chai Nadig Oct 30 '12 at 12:11
  • @chai.nadig: So far everything seems to be as you have specified. How would you like the output to be _different_ from the correct output you have shown? **What is your actual problem?** – hmakholm left over Monica Oct 30 '12 at 12:12
  • @HenningMakholm I don't want a different output. I want the escaping of characters to be done so that I get a string which looks like the one in the output. – Chai Nadig Oct 30 '12 at 12:13
  • @chai.nadig - this can only be answered properly if you state **clearly** what kind of escaping you want. Is it Java String literal escaping? Is it JSON escaping? Is it something else? – Stephen C Oct 30 '12 at 12:16
  • @chai.nadig: If you're already getting the output you want, then what's your problem? It would seem then that you _already_ have the escaping you want in order to get the output you want. – hmakholm left over Monica Oct 30 '12 at 12:18

2 Answers2

3

You can use the String unescapeJava(String) method of StringEscapeUtils from Apache Commons Lang.

example:

String in = "a\\tb\\n\\\"c\\\"";

System.out.println(in);
//This prints
// a\tb\n\"c\"

String out = StringEscapeUtils.unescapeJava(in);

System.out.println(out);
//This prints
// a    b
// "c"

You can see more on How to unescape a Java string literal in Java?

Community
  • 1
  • 1
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
-1

i guess u are looking for that

String a="\"agent\":\"{\\\"name\\\":\\\"James Bond\\\"}q\"";

a=a.replace("\\", "\\\\");
a=a.replace("\"","\\\"");
MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
gabrjan
  • 3,080
  • 9
  • 40
  • 69