nirvair
nirvair

Reputation: 4180

Spring escapes already escaped string

So I have this string that I am saving in database:

{\"facebook\":\"fb.com\",\"twitter\":\"twitter.com\",\"instagram\":\"\",\"googlePlus\":\"\",\"others\":\"espn.com\"}

But when I call the GET api, I get this in JSON

{\\\"facebook\\\":\\\"fb.com\\\",\\\"twitter\\\":\\\"twitter.com\\\",\\\"instagram\\\":\\\"\\\",\\\"googlePlus\\\":\\\"\\\",\\\"others\\\":\\\"espn.com\\\"}

Why is this happening and how can I get the exact same data that is stored in database?

Upvotes: 2

Views: 3777

Answers (3)

Alex Ciocan
Alex Ciocan

Reputation: 2332

You could also use apache's build in StringEscapeUtils.unescapeJson(String input) mechanism for Json data. See reference https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/StringEscapeUtils.html

Upvotes: 1

Pritam Banerjee
Pritam Banerjee

Reputation: 18968

After getting the data, save it in a String and then :

 String newJava = str.replace("\\\", "\");

Upvotes: 0

AntoineB
AntoineB

Reputation: 4694

It is escaped again when you're retrieving the data because Spring thinks that the \ character is part of the data and not used to escape ".

You never want to store escaped characters (be it for JSON special characters, HTML characters in a text, ...), you have to store unescaped data to fix your issue. Escaping has to be done when displaying data, not when storing it.

It is a bad practice to store escaped data because of the problem you're having but also because it will take useless storage space in the database (which might not be a problem right now for you, but will be with millions of rows).

Upvotes: 6

Related Questions