Thomas
Thomas

Reputation: 4330

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?

Upvotes: 7

Views: 7532

Answers (2)

drusya
drusya

Reputation: 288

GSON will automatically escape the string when marshalling it. You don't have to worry about it. You can download gson library from here

Upvotes: 5

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

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.

Upvotes: 7

Related Questions