I've got a string value coming from a database that has to be put into JSON, but the value can contain single and double quotes. Sounds easy enough, right? Well, apparently not in Java 1.4.2. Don't get me started on why it has to be 1.4.2, I inherited this from another developer and we can't update this project yet due to factors beyond my control. :)
So, I have tried all of these (and lots of others just to see the result):
"sample user's string".replaceAll("'", "\'") // returns "sample user's string"
"sample user's string".replaceAll("'", "\\'") // returns "sample user's string"
"sample user's string".replaceAll("'", "\\\'") // returns "sample user's string"
"sample user's string".replaceAll("'", "\\\\'") // returns "sample user\\'s string"
"sample user's string".replaceAll("'", "%%") // returns "sample user%%s string"
All I want is sample user\'s string
, what am I doing wrong? Too bad 1.4.2 doesn't have the String.replace(String,String) function.
Edit: We are using the json-simple
JSON library and I was looking at the output of the above commands in the resultant JSON string. I added additional debug info to see the value before the JSON gets output and it looks like the above commands really are working, but the json-simple
library is stripping the escape chars out.
So, what I'm seeing is:
"sample user's string".replaceAll("'", "\\\\'") // sample user\'s string
myJSONObject.put("value", "sample user's string".replaceAll("'", "\\\\'")) // sample user\\'s string"
myJSONObject.put("value", "sample user's string") // sample user's string
So it looks like the library is not doing its job quite as expected. Does anyone that has used json-simple
know of a workaround for this?