Ealon Ealon - 2 months ago 18
Java Question

Why does Gson add slashes to String

I implemented a simple HttpServlet. The servlet takes requests and calls a third party API to get the data, and then sends data back in response. However, in the response, JSON adds too many slashes.

Does anyone know why?

Below is my code.

public class InstitutionServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Gson gson = new Gson();

String city = request.getParameter("city");
String apiUrl = "https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=" + city;
String data = getInstitutions(apiUrl);

PrintWriter pw = response.getWriter();
gson.toJson(data, pw);

//Get institutions data from API url.
private String getInstitutions(String apiUrl) {
StringBuilder institutions = new StringBuilder();

try {
URL url = new URL(apiUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;

while ((line = bufferedReader.readLine()) != null) {

} catch (Exception e) {

return institutions.toString();

Original data from the API https://inventory.data.gov/api/action/datastore_search?resource_id=38625c3d-5388-4c16-a30f-d105432553a4&q=whatever:

"help": "https://inventory.data.gov/api/3/action/help_show?name=datastore_search",
"success": true,
"result": {
"resource_id": "38625c3d-5388-4c16-a30f-d105432553a4",
"q": "whatever",
"records": [],
"_links": {
"start": "/api/action/datastore_search?q=whatever&resource_id=38625c3d-5388-4c16-a30f-d105432553a4",
"next": "/api/action/datastore_search?q=whatever&offset=100&resource_id=38625c3d-5388-4c16-a30f-d105432553a4"

Data in servlet response

\"success\": true,
\"result\": {
\"resource_id\": \"38625c3d-5388-4c16-a30f-d105432553a4\",
\"q\": \"wahtever\",
\"records\": [],
\"_links\": {
\"start\": \"/api/action/datastore_search?q\u003dwahtever\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\",
\"next\": \"/api/action/datastore_search?q\u003dwahtever\u0026offset\u003d100\u0026resource_id\u003d38625c3d-5388-4c16-a30f-d105432553a4\"


gson.toJson(data, pw) is taking the string data and converting it to JSON, so to do that, it'll escape all characters it needs to in order to create a valid JSON string.

It's not really clear why you need Gson for this scenario, you should be able to write out data to the PrintWriter directly assuming that the other function there is already returning a string in JSON format.