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

时间:2021-12-08 22:27:12

I have this class in a java spring web application.

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

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.

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

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?

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

2 个解决方案

#1


6  

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.

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

#2


3  

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

编组时,GSON会自动转义字符串。你不必担心它。你可以从这里下载gson库

#1


6  

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.

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

#2


3  

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

编组时,GSON会自动转义字符串。你不必担心它。你可以从这里下载gson库