I think you are exposing the problem wrongly.
If you write a String
like this in the source code:
String myText = "Animal:{\"name\":\"turkey\"}";
... the String
is already escaped.
It means you may print :
System.out.println(myText);
... and you would get in output:
Animal:{"name":"turkey"}
... without need of doing anything else.
So I can only imagine two things:
Your question is: Can I write String myText = "Animal:{"name":"turkey"}";
without backslashes in the source code? => The answer is no, or the compiler wouldn't know what's the delimiter of the text and what's just another character of the text.
Your question is missing information: for example, you are receiving this String
from a service which is responding in Json, and over the transport this String
is keeping the backslashes on the quotes.
If that's the case, you should rather use the proper library to parse the message as JsonNode
. Add a dependency to jackson-databind
into your project and then use these methods:
ObjectMapper mapper = new ObjectMapper(); // <-- create ObjectMapper
JsonNode actualObj = mapper.readTree(jsonString); // <-- parse your Json string into a JsonNode
String niceJsonString = actualObj.toPrettyString(); // <-- formats the Json properly
If your question falls in my second guess, then I suggest you have a look at Jackson, it is a pretty powerful library to work with Json (a market standard for Json messaging in Java).