2

I have the String like

[{"Subject":"Java","Teacher":"Pavan"}]

and I want it as

[{\"Subject\":\"Java\",\"Teacher\":\"Pavan\"}]

I tried String toconvert=jsarray.toString().replaceAll("\"", "\\"); also

Thanks in advance

8
  • 2
    Use a library such as Jackson or Gson. Commented Jul 12, 2017 at 9:01
  • 3
    I disagree with the proposed duplicate - this question is about Java, not JavaScript (the proposed duplicate is about JavaScript). Commented Jul 12, 2017 at 9:02
  • 1
    Did you tried replaceAll("\"", "\\\"") ? Commented Jul 12, 2017 at 9:02
  • 1
    Your call to replaceAll is wrong. You are actually replacing a quote by a backslash. It should be String toconvert=jsarray.toString().replaceAll("\"", "\\\""); Commented Jul 12, 2017 at 9:02
  • 1
    @pawansharma Why do you need to make such a conversion? If you want to send data, you should leave the JSON unharmed. Commented Jul 12, 2017 at 9:18

1 Answer 1

2

Maybe:

String toconvert=jsarray.toString().replaceAll("\\\"", "\\\\\""); 

Basically, your code did just replace all quotes with backslash. What you need is to replace all quotes with backslash-quote.

For a simple case as you shown it may be enough, but be aware that this code does not handle the case where the quotes are already escaped (eg. the string "pouet \" pouet" will result in "pouet \\" pouet", thus become invalid)

EDIT: you need to escape the quotes and backslash, once for java, and once for the regexp engine (which have a special meaning for quotes and backslash as well)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.