如何转义要存储在JSON中的字符串

时间:2013-09-20 13:28:50

标签: java javascript json gson

我在java spring web应用程序中有这个类。

public class Question{
    private String questionText;
    //getters and setters.
}

我需要将其转换为json对象。问题是,问题文本可能包含任何内容。这可能是关于json对象的问题,因此json对象本身可能是问题的一部分。我正在使用Google-gson将此类转换为JSON对象。

我是否应该转义questionText,以便在转换为JSON时不会导致问题。如果是,我应该怎么做?如果不是,那么google-gson必须有一些如何逃避questionText来表示它在json对象中。在这种情况下,在客户端,如何使用java脚本将其转换回来并按原样显示给用户?

2 个答案:

答案 0 :(得分:6)

考虑以下示例

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.
}

及其输出

{"questionText":"this \" has some :\" characters that need \\escaping \\"}

需要转义"\的字符已被生成器转义。这是JSON解析器/生成器的优势。

答案 1 :(得分:3)

GSON会在编组时自动转义字符串。 你不必担心它。您可以从here

下载gson库