Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape a string to store in JSON

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?

like image 956
Thomas Avatar asked Sep 20 '13 13:09

Thomas


People also ask

How do you escape a JSON string in Java?

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.

How do you escape a colon in JSON?

You must surround the string value with double quotes. Save this answer.


1 Answers

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.

like image 82
Sotirios Delimanolis Avatar answered Nov 01 '22 18:11

Sotirios Delimanolis