Pavan Kumar
Pavan Kumar

Reputation: 422

How to Stringify the json in java without using js

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

Upvotes: 2

Views: 5846

Answers (1)

spi
spi

Reputation: 1735

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)

Upvotes: 2

Related Questions