How to avoid 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 that the question text can contain anything. This may be a question about the json object, so the json object itself may be part of the question. I am using google-gson to convert this class to a JSON object.

I should avoid the Text question so that it doesn't cause problems when converting to JSON. If so, how do I do this? If not, then google-gson must somehow avoid the Text question in order to represent it in a json object. In this case, on the client side, how can I convert it back using a java script and display it as a user?

+6
source share
2 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 his way out

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

Characters that needed escaping " and \ were generated by the generator. This is the power of JSON Parser / Generators.

+6
source

GSON will automatically delete the row when it is sorted. You have nothing to worry about. You can download the gson library from here

+3
source

Source: https://habr.com/ru/post/954258/


All Articles