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

Pavan Kumar
  • 412
  • 1
  • 6
  • 15
  • 2
    Use a library such as [Jackson](https://github.com/FasterXML/jackson) or [Gson](https://github.com/google/gson). – Jesper Jul 12 '17 at 09:01
  • 3
    I disagree with the proposed duplicate - this question is about Java, not JavaScript (the proposed duplicate is about JavaScript). – Jesper Jul 12 '17 at 09:02
  • 1
    Did you tried `replaceAll("\"", "\\\"")` ? – Zefick Jul 12 '17 at 09: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("\"", "\\\"");` – Pierre Jul 12 '17 at 09:02
  • it should be `replaceAll("\"", "\\\"");` , but the question is why would you want that? – nafas Jul 12 '17 at 09:03
  • actually i need to send data in stringify format . - @nafas – Pavan Kumar Jul 12 '17 at 09:07
  • jsarray.toString().replaceAll("\"", "\\\""); is also not workin -@Pierre – Pavan Kumar Jul 12 '17 at 09:08
  • 1
    @pawansharma *Why* do you need to make such a conversion? If you want to *send* data, you should leave the JSON unharmed. – MC Emperor Jul 12 '17 at 09:18

1 Answers1

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)

spi
  • 1,673
  • 13
  • 19