I have this class in a java spring web application.
public class Question{
private String questionText;
//getters and setters.
}
I need to convert this to a json object. The problem is, the question text may contain anything. It could be a question about a json object, so a json object itself may be a part of the question. I'm using Google-gson to convert this class to a JSON object.
Should I escape the questionText so that it wont cause a problem while converting to JSON. If yes, how should I do it? If no, then google-gson must some how escape the the questionText to represent it within the json object. In that case, at the client side, how can I convert it back using java script and display to the user as it is?
You can escape String in Java by putting a backslash in double quotes e.g. " can be escaped as \" if it occurs inside String itself. This is ok for a small JSON String but manually replacing each double quote with an escape character for even a medium-size JSON is time taking, boring, and error-prone.
You must surround the string value with double quotes. Save this answer.
Consider the following example
public static void main(String[] args) {
Question q = new Question();
q.questionText = "this \" has some :\" characters that need \\escaping \\";
Gson g = new Gson();
String json = g.toJson(q);
System.out.println(json);
}
public static class Question{
public String questionText;
//getters and setters.
}
and its output
{"questionText":"this \" has some :\" characters that need \\escaping \\"}
The characters that needed escaping "
and \
have been escaped by the generator. This is the strength of JSON Parser/Generators.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With