How to Format a Json String?

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?

0

2 Answers

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\"}"
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.