3

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 2

2

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\"}"
Sign up to request clarification or add additional context in comments.

1 Comment

That was a really neat trick I would never have thought of, good job sir!
0

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.

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.