ThatNewGirl
ThatNewGirl

Reputation: 57

How to format a json string?

I want to convert

{"name":"john","age":22,"class":"mca"}

to

"{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}"

How can I do this using Gson library? Or is there another way to do this?

Upvotes: 3

Views: 25050

Answers (2)

D.B.
D.B.

Reputation: 4713

Once you have the JSON String you can just use toJson on it like this:

    Gson gson = new Gson();
    String json = "{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}";

    System.out.println("original: "+json);

    String escaped = gson.toJson(json);
    System.out.println("escaped: "+escaped);

Output:

original: {"name":"john","age":22,"class":"mca"}
escaped: "{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}"

Upvotes: 2

JRG
JRG

Reputation: 4177

There are lots of online tools that can help you do so, here are few ...

Programmatically, if you have input as JSON Object then you can just print the JSONObject using toString(); you would need escape characters in JSON string only if you are using it as a string itself in the code mostly for testing (UT or FT).

But if you still insist on escaped JSON String then you can use string replaceAll() on JSONObject toString() and have all double quotes replaced with escape character and double quotes.

Upvotes: 0

Related Questions